2013-07-05 33 views
1

嗨我一直在試圖通過java插入一個字符串到sqlite數據庫。但是我在值sql語句中傳遞的字符串參數在其中包含引號作爲內容。我在想這是我得到的錯誤爲什麼它沒有插入到數據庫中。有沒有辦法繞過插入語句中的引號。謝謝。字符串參數插入語句中的引號

這是代碼:

public void addNote(String topicadd, String contentadd) throws Exception 
{ 
    try 
    { 
     getConnection(); 
     statement = conn.createStatement(); 
     statement.executeUpdate("insert into tbl_notes (notes_topic, notes_content) values ('" + topicadd + "', '" + contentadd +"')"); 
     System.out.println("inserted note"); 
    } 
    catch (Exception m) 
    {`enter code here` 
     System.out.println("error insert topic"); 
     System.out.println(m.getMessage()); 
    } 
} 

這是參數類長......這一切都是在contentadd

import java.sql.*; 

Resultset rset = null; (this has no new ResultSet() initialization) 
Connection conn = null; (this has no new initialization too...) 
Statement statement = null; (this has now new initialization) 

always..... 
try 
{ 

} 
catch (Exception e) <- can switch e for any other alphabet 
{ 
    e.getMessage(); 
    System.out.println("error this module"); <- personal practice 
    throw e; 
} 

- getting connection 

Class.forName("org.sqlite.JDBC"); 
conn = DriverManager.getConnection("jdbc:sqlite:m.db"); 
*** this is sqlite connection format 'm.db' is the database name 

establish connection first.. 
statement syntax follows: 
statement = conn.createStatement(); 
rset = statement.executeQuery("select * from tbl_notes"); 
- executeQuery is used for SELECT sql statements 
rset = statement.executeUpdate("insert into tbl_notes (ID, status) values 
('100', 'status here'); 

整個文本字符串contentadd,我正在做一個簡短的筆記程序...嗯,它不執行插入語句...在命令提示符附近(從文本中的字)的某處錯誤...我使用sqlite ...請讓我知道,如果你需要更多細節。再次感謝你。

+0

你可以發表一些代碼嗎? – Seth

+2

[使用參數化查詢。](http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html) –

+0

對不起,我發佈了代碼現在。謝謝。 – buencamino

回答

2

使用PreparedStatement插入包含特殊字符值:

getConnection(); 
PreparedStatement statement = conn.prepareStatement("insert into tbl_notes (notes_topic, notes_content) values (?, ?)"); 
statement.setString(1, topicadd); 
statement.setString(2, contentadd); 
statement.executeUpdate(); 

正如你看到的,你可以使用參數與PreparedStatement也可以包含引號。

此外,您還可以獲得一些針對SQL注入的保護,因爲給予PreparedStatement的字符串會相應地轉義。

相關問題