1. 程式人生 > >java中PreparedStatement解決需轉義字元向資料庫中插入時的轉義問題

java中PreparedStatement解決需轉義字元向資料庫中插入時的轉義問題

簡單的執行如下語句去做資料庫的插入操作是有問題的!它處理不了單引號,雙引號等需要轉義的字元的插入問題!

String sql = "insert into emailOriginal(id,date,subject,source,target" +
") value(\""
+ vo.getId() + "\",\"" 
+ vo.getDate()+"\",\"" 
+ vo.getSubject()+"\",\""
+ vo.getSource()+"\",\""
+ vo.getTarget()+"\");";

               。。。

pstmt = dbc.getConnection().prepareStatement(sql);

。。

pstmt.execute(sql);

會有如下錯誤:

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 'notional" stuff

經過查詢發現是插入“nation”時,雙引號沒有經過轉義!

現在修改成使用PreparedStatement,用?預處理查詢條件,會避免上述簡單的字串拼接造成的轉義問題。

		String sql = "insert into emailOriginal(id,date,subject,source,target" +
					") value(?,?,?,?,?);";
		
		
		PreparedStatement pstmt = null;
		try {
			pstmt = dbc.getConnection().prepareStatement(sql);
			pstmt.setString(1, vo.getId());
			pstmt.setString(2, vo.getDate());
			pstmt.setString(3, vo.getSubject());
			pstmt.setString(4, vo.getSource());
			pstmt.setString(5, vo.getTarget());
			pstmt.execute();
			//pstmt.execute(sql);
			pstmt.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
其中的
pstmt.setString(1, vo.getId());
會幫助字串轉義。 可以插入如下的記錄了:
+------+------+--------+--------+----------+
| id   | date | source | target | subject  |
+------+------+--------+--------+----------+
| id   | date | source | target | "subject |
| id   | date | source | target | 'subject |
+------+------+--------+--------+----------+