2012-07-04 89 views
0

我在MySQL數據庫從Java文件中使用插入值 -錯誤插入查詢

String query = "INSERT INTO genes (sent, title) VALUES ('"+sent+"','"+title+"')"; 
Statement stmt = con.createStatement(); 
int rs = stmt.executeUpdate(query); 

其中senttitle是運用一些算法後提取變量字符串。但是,當senttitle包含單個qoutes時,會給出sql錯誤。

+0

考慮使用iBATIS/MyBatis的: http://blog.mybatis.org/ 或者JPA。 –

回答

4

考慮使用準備好的語句與參數:

PreparedStatement pstmt = con.prepareStatement(
    "INSERT INTO genes (sent, title) VALUES (?, ?)"); 
pstmt.setString(1, sent); 
pstmt.setString(2, title); 
pstmt.executeUpdate(); 
3

你應該在填充使用PreparedStatement查詢參數。它處理輸入參數中的任何單引號。

修改您的查詢語句對象如下所示,應該工作:

String query = "INSERT INTO genes (sent, title) VALUES (? , ?)"; 
PreparedStatement pst = con.prepareStatement(query); 
pst.setString(1, sent); 
pst.setString(2, title); 

int insertResult = pst.executeUpdate(); 
1

您應該使用PreparedStatements了點。 PreparedStatement位於java.sql.*命名空間下。

String insertString = "INSERT INTO genes (sent, title) VALUES (?,?)"; 
// con is your active connection 
PreparedStatement insertX = con.prepareStatement(updateString); 
insertX.setString(1, sent); 
insertX.setString(2, title); 
insertX.executeUpdate(); 
1

你應該從不將SQL語句是這樣,而是使用prepared statements

String query = "INSERT INTO genes (sent, title) VALUES (?,?)"; 
PreparedStatement stmt = con.prepareStatement(query); 

p.setString(1, sent); 
p.setString(2, title); 
p.executeUpdate(); 

如果你用你自己暴露於危險sql-injection攻擊的字符串連接方法。

+0

+1因爲唯一的答案提到sql注入。看到其他人沒有提到這一點很可怕。 – Axel

0

請從字符串中刪除'或將其替換爲\''

Mysql只允許在\'格式的特殊字符。

1
String query = "INSERT INTO genes (sent, title) VALUES (?, ?)"; 
PreparedStatement pt = con.prepareStatement(query); 
pt.setString(1, sent); 
pt.setString(2, title); 
pt.executeUpdate();