为了进行测试,我创建了一个包含2个jTextField,一个按钮和一个表的表单。我正在尝试将数据添加到数据库。但是我似乎遇到了一个问题。当我按下按钮时,它返回失败消息,因为尚未将数据添加到数据库中。我将不胜感激。所以这就是我在做什么。我创建了ConnectionConfiguration类以简化代码:
public class ConnectionConfiguration {
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connection Success");
} catch(ClassNotFoundException e) {
System.out.println("Connection Failed");
}
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/systemnew?zeroDateTimeBehavior=convertToNull", "root","123456");
System.out.println("Database Connected");
} catch (SQLException se){
System.out.println("No Database" + se);
}
return connection;
}
}
连接始终是成功的,而数据库始终是连接的。错误消息指出我的错误在这里(在systemnew.UpdateDatabase.add处)。这是UpdateDatabase类的add方法:
public boolean add(String field1, String field2) {
try {
Connection conn = ConnectionConfiguration.getConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO newtable(field1,field2) VALUES('"+field1+"','"+field2+"')");
ps.executeUpdate();
return true;
} catch(Exception ex){
ex.printStackTrace();
}
return false;
}
以下是按钮的代码,该按钮应该可能会将数据添加到数据库中:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(new UpdateDatabase().add(jTextField1.getText(),jTextField2.getText())){
JOptionPane.showMessageDialog(null, "Added successfully!");
} else {
JOptionPane.showMessageDialog(null, "Record has not been added!");
}
}
错误
Connection Success
Database Connected
java.sql.SQLException: Field 'tblid' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2073)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2009)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5098)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1994)
at systemnew.UpdateDatabase.add(UpdateDatabase.java:38)
错误说明了具体问题
java.sql.SQLException: Field 'tblid' doesn't have a default value
您的表newtable
似乎具有非nulltblid
列,在插入过程中未为其指定任何值。您可能需要将其标记为auto increment
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句