2013-05-27 92 views
0

大家晚安。我有這些代碼。我只在這裏複製了有問題的代碼。向Java數據庫插入數據時出錯,使用Java

//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) 

回答

1

發生這種情況,因爲你需要圍繞它不帶引號的整數變量,否則數據庫會理解他們作爲列,只需添加引號不是整數列,如

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

我認爲customer_cardnocustomer_phonedebt是ING我tegers列,如果他們只是NIT環繞variabkes用引號

1

兩件事情:

首先,SQL注入風險。我建議你把預處理語句上一看:http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

現在,如果你堅持在建立查詢字符串一樣,你應該附上String值要插入引號:

statement.executeUpdate("INSERT INTO Customer " + 
    (customer_cardno, customer_name, customer_sirname, customer_phone, debt) " + 
    VALUES(" + num + ", '" + name + "', '" + surname + "', '" + phone + "', " + debt + ")"); 
/* 
* Notice the single quotes arround "name", "surname" and "phone" 
*/ 
+0

謝謝你,在你面前回答,我找到了。 =)再次感謝。 –

+0

@ArdaOğulÜçpınar無論如何,請閱讀我提供給您的鏈接。您的代碼易受SQL注入攻擊。準備好的陳述可以爲您節省很多痛苦(而且它們非常易於使用) – Barranka

+0

非常感謝! –

相關問題