2012-02-09 93 views
2

晚上好。插入數據到表

我正在做一個基本的練習,將數據插入到Access數據庫表中,並且在代碼中存在一個語法錯誤,我正在努力查明。

希望能得到一些關於語法問題所在的幫助。

錯誤讀取如下 java.sql.SQLException:[Microsoft] [ODBC Microsoft Access Driver]查詢值和目標字段的數目不相同。

public void addData(String ID, String name, String address, String type) throws SQLException 
{ 
    int rowsadded; 
    Statement statement = conn.createStatement(); 
    String queryString = "INSERT INTO Artists(ID, Name, Address, Type) VALUES (" + ID + ", '" + name + "', '" + address + ", " + type + "')"; 

    System.out.println(queryString); 
    System.out.println(ID + "(ID) added to the database"); 
    rowsadded = statement.executeUpdate(queryString); 
    System.out.println("Rows updated = " + rowsadded); 
} 

方法調用發生如下

Insertingdata example; 
    try 
    { 
     example = new Insertingdata(); 

     example.addData("15", "Bob Dylan", "Los Angeles", "Folk"); 

    } 
    catch(SQLException se) 
    { 
     se.printStackTrace(); 
    } 
    catch(ClassNotFoundException ce) 
    { 
     ce.printStackTrace(); 
    } 

回答

4

你錯過了兩個單引號的查詢,所以地址和類型都被視爲單一的價值。將您的queryString行替換爲:

String queryString = "INSERT INTO Artists(ID, Name, Address, Type) VALUES (" + ID + ", '" + name + "', '" + address + "', '" + type + "')"; 

這應該可以解決問題。

+0

(+1)並避免使用預準備語句的這種錯誤! – soulcheck 2012-02-09 16:30:40

+0

謝謝。愚蠢的錯誤 – Arianule 2012-02-09 17:25:32