出于测试目的,我创建了一个包含2个jTextFields,按钮和表格的表单。我正在尝试将数据添加到数据库。但我似乎遇到了一个问题。当我按下按钮时,它返回失败消息,因为数据尚未添加到数据库。我很感激任何帮助。所以这就是我正在做的事情。我创建了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类的添加方法:
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)
答案 0 :(得分:1)
在您的表newtable
中,有一个名为tblid
的字段,您没有为其分配值,因此您会收到以下错误
字段'tblid'没有默认值
顺便说一下,使用PreparedStatement以避免可能的Sql注入会更安全
另请考虑此answer以了解自动递增ID字段
答案 1 :(得分:0)
错误告诉具体问题
java.sql.SQLException: Field 'tblid' doesn't have a default value
您的表newtable
似乎具有非空tblid
列,您在插入期间未指定任何值。您可能希望将其标记为auto increment