2015-12-14 27 views
0

插入過程中Mysql的日期欄的錯誤,我想用JDBC插入數據,每當我執行程序就說明我一些MySQL錯誤:從Java

Insert語句:

String sql = "INSERT into books(name, isbn, author, category, desc, published) VALUES('"+name+"','"+isbn+"','"+author+"','"+category+"', '"+desc+"','"+book_published+"')"; 

我試圖將字符串轉換使用到這裏日期:

String yr = year.getSelectedItem().toString(); 
String mn = month.getSelectedItem().toString(); 
String dy = day.getSelectedItem().toString(); 
String book_date = yr+"-"+mn+"-"+dy; 
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", 
              Locale.ENGLISH); 
try{ 
Date book_published = df.parse(book_date); 
}catch(...){...} 

,它顯示了我錯誤如:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, published) VALUES('skd flakj','klsdjf askj','kl jasdklfj kl','kls djfklj f' at line 1 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 

請幫我弄清楚這裏有什麼問題。

+0

您的一個值是否有一個流浪的單引號?通過使用參數綁定而不是直接在SQL字符串中連接值,可以避免很多麻煩。 – sstan

+3

[Using Prepared Statements](http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html) – MadProgrammer

回答

0

desc不是一個特別好的列名,因爲它是MySQL中的一個保留字。我不知道這是否是這裏唯一的問題,但你可能想嘗試周圍desc蜱,像這樣:

String sql = "INSERT into books(`name`, `isbn`, `author`, `category`, `desc`, `published`) VALUES('"+name+"','"+isbn+"','"+author+"','"+category+"', '"+desc+"','"+book_published+"')"; 

這是很好的做法呢。

編輯:正如其他人所提到的,在將不可信輸入保存到數據庫時,準備好的語句更安全。

+0

thanx @josh我懂了:) –

+0

很高興幫助! @Uraz –

3

由於使用正常的查詢語句,您的代碼很容易出現SQL注入攻擊。爲了保護您的查詢使用preparedstatement。

根據您的查詢問題,DESC是一個保留字。因此,您不能將其用作列名。查看this以獲取保留字的完整列表。