2013-09-30 177 views
-1

嗨,我想插入MySQL數據庫中的值,並附上我的代碼下面,我收到錯誤。下面在MySQL數據庫中插入查詢


try{ 
    Class.forName("com.mysql.jdbc.Driver"); 
    Connection con = DriverManager.getConnection(DB_URL,"root","root"); 
    System.out.println("Remote DB connection established"); 
    PreparedStatement statement=con.prepareStatement("INSERT INTO TBL_MONTHLY_EXPENSES_DETAILS"+ 
    (AVG_COST, RWDS_INCENT,OTH_EXPENSES,TRAVELLING_EXPENSES,CLIENT_VISITS,REV_RECD)VALUES 
    (AVG_COST, RWDS_INCENT,OTH_EXPENSES,TRAVELLING_EXPENSES,CLIENT_VISITS,REV_RECD); 
}catch(Exception e){ 
    System.out.println("Remote DataBase connection establishment error."); 
    e.printStackTrace(); 
    pn.setProjectName("Failed"); 
    System.out.println(e.getMessage().toString()); 
} 
+0

con.prepareStatement()調用中是否缺少一些引號? – TheWolf

+0

需要查看實際的異常消息以幫助 –

+0

我在查詢中遇到錯誤。 – Numaish

回答

1

更正 - 你丟失了一些報價,而你沒有正確參數化。

try 
     { 
      Class.forName("com.mysql.jdbc.Driver"); 
      Connection con = DriverManager.getConnection(DB_URL,"root","root"); 
      System.out.println("Remote DB connection established"); 
      PreparedStatement statement=con.prepareStatement("INSERT INTO TBL_MONTHLY_EXPENSES_DETAILS"+ 
        "(AVG_COST, RWDS_INCENT,OTH_EXPENSES,TRAVELLING_EXPENSES,CLIENT_VISITS,REV_RECD)VALUES"+ 
        "(?,?,?,?,?,?)"); 


    }catch(Exception e) 
    { 
     System.out.println("Remote DataBase connection establishment error."); 
     e.printStackTrace(); 
     pn.setProjectName("Failed"); 
     System.out.println(e.getMessage().toString()); 
    } 

不要忘記使用statement.setX()函數來設置每個值的值嗎?在VALUES語句中。

+0

有一些支架丟失 – Numaish

0
int AVG_COST, RWDS_INCENT, OTH_EXPENSES, TRAVELLING_EXPENSES,CLIENT_VISITS, REV_RECD; 

PreparedStatement statement=conn.prepareStatement("INSERT INTO TBL_MONTHLY_EXPENSES_DETAILS" + 
      "(AVG_COST, RWDS_INCENT,OTH_EXPENSES,TRAVELLING_EXPENSES,CLIENT_VISITS,REV_RECD)" + 
      "VALUES(?,?,?,?,?,?)"); 

statement.setInt(1, AVG_COST); 
statement.setInt(2, RWDS_INCENT); 
statement.setInt(3, OTH_EXPENSES); 
statement.setInt(4, TRAVELLING_EXPENSES); 
statement.setInt(5, CLIENT_VISITS); 
statement.setInt(6, REV_RECD); 
statement.executeUpdate(); 
+1

而不是使用preparedStatement中的變量,對它進行參數化以便它可以彈性注入。使用這些參數還允許重新使用準備好的語句。不重複使用preparedStatement會導致重複插入時性能下降。 – Talandar

+0

感謝Talandar。 :) – Piyush

+0

假設我想存儲在數據庫中PJT_CODE和PJT_MONTH和PJT_YEAR – Numaish