我正在将一些数据插入到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();
} 发布于 2015-06-04 15:47:41
您应该省略自动生成的列"uniqueID“,并重写代码。例如。
String query4 = "insert into ProjectImages (Path) values(?)";另一种方法-为自动生成的列传递空值。例如。
String query4 = "insert into ProjectImages (uniqueId, Path) values(null,?)";发布于 2015-06-04 16:28:27
如果没有堆栈跟踪,可能很难找到不起作用的地方。它可能是索引约束异常,空指针异常,...但是,我建议使用不同的日期格式,而不是
day1.getText()+"/"+month1.getText()+"/"+year1.getText()我会用
year1.getText()+"-"+month1.getText()+"-"+day1.getText()(请查看MySQL文档,特别是STR_TO_DATE()函数,但您可能不需要它)。
还有改进你的代码的空间(遵循Rajesh的评论):
虽然你可能使用的是Java7或更高版本,但我会为connection;
https://stackoverflow.com/questions/30637504
复制相似问题