我有一個問題,即向我通過JDBC創建的表中插入新的數據行。它在ExecuteUpdate()行之後引發SQLException。無法使用jdbc在數據庫中插入數據到數據庫
下面我提供了一個在DB中創建DB和表的代碼。第二部分的代碼應該將值插入到患者數據表中的行中。
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();
}
}
上面的代碼工作正常,拋出沒有例外。我假定兩個表已經創建和DB存在:)
不是這是應該插入數據的一部分:
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;
}
}
行:結果= ps.executeUpdate();拋出SQLException,我不知道錯誤在哪裏。我已將derby.jar添加到我的構建路徑中。
請張貼異常詳情。 – MByD 2012-04-08 13:10:18
請顯示異常錯誤消息和堆棧跟蹤 – Thilo 2012-04-08 13:11:36
'java.sql.SQLIntegrityConstraintViolationException:語句被中止,因爲它會在'PATIENTSDATA'上定義的'SQL120407181654820'標識的唯一或主鍵約束或唯一索引中導致重複鍵值」。 \t at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)' – user1158803 2012-04-08 13:19:28