2012-06-28 30 views
1

我目前正在編寫一個Java應用程序,用於執行Swing GUI組件的輸入/輸出以及從本地Microsoft Access 2007數據庫存儲/檢索此數據。除非我嘗試更新記錄,並且輸入來自要存儲在文本或備註字段中的JTextArea,否則一切都會順利進行。我可以接受來自JTextField的罰款,但是我得到了「SQLException:UPDATE語句中的語法錯誤」。與一個JTextArea。從Swing中將JTextArea存儲在Access 2007數據庫中

這裏是有問題的代碼:

/* <in_some_method> */ 
myJTextArea.setText(someString); // the components can have the exact 
myJTextField.setText(someString); // same string and still have problems 

saveEdit(myTable, myColumn, myJTextField.getText(), myID); // this works fine 
saveEdit(myTable, myColumn, myJTextArea.getText(), myID); // this throws an exception 
/* </in_some_method> */ 

/* the update method */ 
public void saveEdit(String table, String column, String value, long id) { 
    String query = "UPDATE " + table + " "; 
    query += "SET " + column + " = '" + value + "', " 
    query += "UpdatedAt = Now() "; 
    query += "WHERE ID = " + id; 

    try { 
     // conn is a working connection to the database 
     Statement s = conn.createStatement(); 

     // execute the query 
     s.executeUpdate(query); 

     // close open database handle 
     s.close(); 

    } catch (Exception ex) { 
     System.err.println(ex); 
    } 
} 

幾件事情:

  • 我不認爲它與數據庫中的字段的數據類型存在;我已經爲類型嘗試了備註和文本,並且都使用JTextField並且都不能與JTextArea一起使用。

  • 如上所述,異常是「SQLException:UPDATE語句中的語法錯誤」。所以我知道我的問題與數據庫表的佈局無關;所請求的表和列都存在並且可以被訪問。

有人有什麼想法嗎?任何幫助將不勝感激。當設置爲JTextArea也不會同時

+0

myJTextArea.getText()的值是什麼? – Thinhbk

回答

1

我不知道什麼是someString,但我打賭它包含新行或如此,所以設置成JTextField這將是在「扁平化」。所以,當得到時,你會有兩個不同的字符串,一個可以正常工作,另一個會導致語法錯誤。

無論是什麼情況,您應該先將escape字符串保存到數據庫中,否則將冒着SQL injection的風險。這也將確保您的方法對兩個組件都正常工作(雖然由於上述原因,確切的字符串可能仍然不同)。

1

我同意mgibsonbr,它是可以SQL SQL注入。這是另一個tutorial如何去使用它們

但是,對於你的直接問題,鑑於使用文本字段的getText()檢索到的字符串已經工作,你可能試圖存儲使用getText()從你的JTextArea並檢查它是什麼?或者甚至試圖在你的JTextArea的getText方法上調用修剪功能,所以沒有空格等。

也許這個someString沒有爲JTextArea設置正確?

相關問題