我将一些数据插入mySql数据库。由于某些未知原因,数据未插入到我的表中。这适用于SQLITE。 这是我的代码:
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
String query1 = "insert into Project (uniqueid,name,address,startingdate,estcompletion,engname) values(?,?,?,?,?,?)";
String query2 = "insert into EngineerData (UniqueId,Name,Password) values(?,?,?)";
String query3 = "insert into " +tableName +" (UniqueId,Category,Item,EstimatedQuantity,Unit,UnitPrice,TotalPrice,TotalSpent) values(?,?,?,?,?,?,?,?)";
String query4 = "insert into ProjectImages (uniqueId, Path) values(?,?)";
PreparedStatement pst1= conn.prepareStatement(query1);
PreparedStatement pst2 = conn.prepareStatement(query2);
PreparedStatement pst3 = conn.prepareStatement(query3);
PreparedStatement pst4 = conn.prepareStatement(query4);
pst1.setInt(1, uniqueID);
pst1.setString(2, projectName.getText());
pst1.setString(3, address.getText());
pst1.setString(4, day1.getText()+"/"+month1.getText()+"/"+year1.getText());
pst1.setString(5, day2.getText()+"/"+month2.getText()+"/"+year2.getText());
pst1.setString(6, engineerName.getText());
pst2.setInt(1, uniqueID);
pst2.setString(2, engineerName.getText());
pst2.setString(3, engineerPassword.getText());
try{
for (int j = 0; j < table.getRowCount(); j++ ){
pst3.setInt(1, uniqueID);
pst3.setString(2, table.getValueAt(j, 0).toString());
pst3.setString(3, table.getValueAt(j, 1).toString());
pst3.setString(4, table.getValueAt(j, 2).toString());
pst3.setString(5, table.getValueAt(j, 3).toString());
pst3.setString(6, table.getValueAt(j, 4).toString());
pst3.setString(7, table.getValueAt(j, 5).toString());
pst3.setDouble(8, 0.0);
pst3.execute();
}}catch(Exception e3){
/*JOptionPane.showMessageDialog(null, e3);
*
*/
}
pst4.setInt(1, uniqueID);
pst4.setString(2, null);
pst1.execute();
pst2.execute();
pst4.execute();
System.out.println(pst1.toString());
System.out.println(pst2.toString());
pst1.close();
pst2.close();
pst3.close();
pst4.close();
conn.close();
}
答案 0 :(得分:2)
您应该省略自动生成的列“uniqueID”并重写您的代码。 实施例
String query4 = "insert into ProjectImages (Path) values(?)";
另一种方法 - 为自动生成的列传递空值。实施例
String query4 = "insert into ProjectImages (uniqueId, Path) values(null,?)";
答案 1 :(得分:0)
如果没有堆栈跟踪,可能很难找到不起作用的地方。它可能是一个INDEX约束异常,一个空指针异常,......但是,我建议格式化不同的日期,而不是
day1.getText()+"/"+month1.getText()+"/"+year1.getText()
我使用
year1.getText()+"-"+month1.getText()+"-"+day1.getText()
(查看MySQL文档,特别是 STR_TO_DATE()函数,但您可能不需要它。)
还有改进代码的空间(遵循Rajesh的评论):