我正在使用Java、Spring Boot和H2数据库开发一个帐户服务项目,下一步是使用sql实现添加员工工资。
这是相关代码供参考:
@PostMapping("/api/acct/payments")
public ResponseEntity<?> postPayrolls(@Valid @RequestBody UserPayroll[] payrolls) throws SQLException {
try (Connection connection = DriverManager.getConnection(url)) {
connection.setAutoCommit(false);
try (PreparedStatement createTable = connection.prepareStatement("CREATE TABLE IF NOT EXISTS payrolls(" +
"employee VARCHAR(20)," +
"period VARCHAR(20)," +
"salary INTEGER");
PreparedStatement statement = connection.prepareStatement(
"INSERT INTO payrolls (employee, period, salary) VALUES (?, ?, ?)" )) {
createTable.executeUpdate();
for (UserPayroll payroll : payrolls) {
statement.setString(1, payroll.getEmployee());
statement.setString(2, payroll.getPeriod());
statement.setLong(3, payroll.getSalary());
statement.executeUpdate();
}
connection.commit();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
} catch (SQLException e) {
System.out.println("1 " + e.getMessage());
}
Map<String, String> response = new HashMap<>();
response.put("status", "Added successfully!");
return ResponseEntity.ok().body(response);
}
public class UserPayroll {
private String employee;
@Pattern(regexp = "^(0[1-9]|1[0-2])-(20\\d{2}|19\\d{2})$")
private String period;
@Min(1)
private Long salary;
//Constructors, Getters and Setters
}
这是我在尝试创建工资单表时遇到的错误:
SQL 语句“CREATE TABLE IF NOT EXISTS payrolls(employee VARCHAR(20),period VARCHAR(20),salary INTEGER[*]”中存在语法错误;预期为“ARRAY, INVISIBLE, VISIBLE, NOT NULL, NULL, AS, DEFAULT,已生成、更新时、非空、空、自动增量、空默认、NULL_TO_DEFAULT、序列、选择性、注释、约束、注释、主键、唯一、非空、空、检查、引用、自动增量、、、)”; SQL语句: 如果不存在则创建表工资单(员工 VARCHAR(20)、期间 VARCHAR(20)、工资 INTEGER [42001-214]
当用户输入 url 时,他们必须提供 UserPayrolls 列表,然后必须将其添加到数据库中。但是,会引发 SQL 异常,因此数据库中不会保存任何内容。
您需要在此处添加右括号:
"salary INTEGER)");