gpt4 book ai didi

java - 使用 Java 将数据插入 mySQL DB 时出错

转载 作者:行者123 更新时间:2023-11-29 08:30:25 25 4
gpt4 key购买 nike

大家晚安。我有这些代码。我只是将有问题的代码复制到这里。

//This is my main method. I called my Database.class, made the connection and called the insertnewcustomer method.

public static void main(String[] args) {
Database db = new Database();
db.connectDB();
db.insertNewCustomer(86754312, "arda", "zenci", 55418, 400);
.................//

//and here is my insertNewCustomer method which is inside the Database.class

public void insertNewCustomer(int num, String name, String surname, int phone, int debt){
try {
statement.executeUpdate("INSERT INTO Customer(customer_cardno, customer_name, customer_sirname, customer_phone, debt) VALUES(" + num + ", " + name + ", " + surname + ", " + phone + ", " + debt + ")");
} catch (SQLException e) {
e.printStackTrace();
}}

我看不到任何问题,但我有一个 MySQLSyntaxErrorException

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'arda' in 'field list'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2809)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1811)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1725)
at Database.insertNewCustomer(Database.java:39)
at mainFrame.main(mainFrame.java:50)

最佳答案

发生这种情况是因为您需要用引号将非整数的变量括起来,否则数据库会将它们理解为列,只需在非整数列中添加引号,例如

statement.executeUpdate("INSERT INTO Customer(customer_cardno, customer_name, customer_sirname, customer_phone, debt) VALUES(" + num + ", '" + name  + "', '" + surname + "', " + phone + ", " + debt + ")");

我假设customer_cardnocustomer_phonedebt是i tegers列,如果它们不是只是用引号包围variabkes

关于java - 使用 Java 将数据插入 mySQL DB 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16781601/

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