我在通过 JDBC 创建的表中插入新数据行时遇到问题。它在 ExecuteUpdate() 行之后抛出 SQLException。
下面我提供了一个在该数据库中创建数据库和表的代码。第二部分的代码应该将值插入到 PatientData 表的行中。
public class DbSetUp {
private static Connection con;
private static String mySqlString = "CREATE TABLE PatientsData" +
"(id INTEGER PRIMARY KEY," +
"fname VARCHAR(30) NOT NULL," +
"lname VARCHAR(30) NOT NULL," +
"sex VARCHAR(1) NOT NULL," +
"insurance VARCHAR(1) NOT NULL," +
"profession VARCHAR(30) NOT NULL)";
//private boolean end;
private static String strTemp = "CREATE TABLE PatientsTemp" +
"(id INTEGER PRIMARY KEY," +
"name VARCHAR(256) NOT NULL," +
"date DATE NOT NULL," +
"temp NUMERIC NOT NULL)";
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch (ClassNotFoundException e) {
System.out.println("Driver not found");
e.printStackTrace();
}
try {
con = DriverManager.getConnection("jdbc:derby:PatientDb;create=true");
} catch (SQLException e) {
System.out.println("Db not found");
e.printStackTrace();
}
Statement statement = null;
try{
statement = con.createStatement();
statement.execute(mySqlString);
statement.execute(strTemp);
} catch(SQLException ex){
ex.printStackTrace();
}
}
上面的代码工作正常,没有异常。我假设两个表都已创建并且数据库存在:)
不是应该插入数据的部分:
public Patient createNewPatient(int id, String fname, String lname,
String sex, String insurance, String profession) {
try {
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
} catch (SQLException e1) {
System.out.println("to na poczatku");
e1.printStackTrace();
}
try{
con = DriverManager.getConnection("jdbc:derby:PatientDb");
PreparedStatement ps = con.prepareStatement("INSERT INTO PatientsData VALUES(?,?,?,?,?,?)");
System.out.println("Prepared Statement");
ps.setInt(1, id);
System.out.println("set int id");
ps.setString(2, fname);
ps.setString(3,lname);
ps.setString(4,sex);
ps.setString(5, insurance);
ps.setString(6,profession);
System.out.println("set string profession");
result = ps.executeUpdate();
System.out.println(result);
return new Patient(id,fname,lname,sex,insurance,profession);
//System.out.println("set string profession");
} catch(SQLException e){
System.out.println("SQL exception");
return null;
}
}
行:result = ps.executeUpdate(); 抛出 SQLException,我不知道错误在哪里。我已将 derby.jar 添加到我的构建路径中。