gpt4 book ai didi

java - 向MySQL数据库添加数据

转载 作者:行者123 更新时间:2023-11-28 23:25:52 25 4
gpt4 key购买 nike

出于测试目的,我创建了一个带有 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)

最佳答案

在您的表 newtable 中,有一个名为 tblid 的字段,您没有为其分配值,因此会出现以下错误

Field 'tblid' doesn't have a default value

顺便说一句,使用 PreparedStatement 会更安全为了避免可能的 Sql 注入(inject)

同时考虑这个 answer了解有关自动递增 id 字段的信息

关于java - 向MySQL数据库添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39380938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com