問題描述:
“描述”表單字段如果輸入含英文一撇(')的字符串(如“param's num.”),則保存時MyEclipse報錯(提示:'?' 附近有語法錯誤。)。並且保存不了。
因爲之前用C# MVC開發,使用的是LINQ TO SQL,沒有留意這樣的問題。(如一網友所說“微軟的數據訪問技術LINQ向.net開發人員提供了徹底地清除SQL注入漏洞的機會”,哈。。)
現狀描述:查看執行保存的servlet方法,使用的是Statement。
網上查,找到了PreparedStatement(https://www.cnblogs.com/huangwentian/p/7051109.html)。
參照以下網址(https://blog.csdn.net/weixin_42166907/article/details/81277282)做了測試,可以保存了。
說明:我只將保存爲字符串的字段通過傳參方式傳給需要調用的、保存數據的方法。
保存數據的方法代碼如下:
public int execUpdate_private(String sql,String p1,String p2,String p3,String p4) {
Connection con = null;
PreparedStatement psmt = null;
try {
con = getCon();
//獲得預處理對象
psmt = con.prepareStatement(sql);
psmt.setQueryTimeout(20); // set timeout to 20 sec.
//設置實際參數
psmt.setString(1, p1);
psmt.setString(2, p2);
psmt.setString(3, p3);
psmt.setString(4, p4);
return psmt.executeUpdate();} catch (Exception e) {
e.printStackTrace();} finally {
try {
if( psmt != null ) {
psmt.close();
psmt = null;
}
if( con != null ) {
con.close();
con = null;
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return -1;
}
以上已經可以實現我這個頁面的(含'的)數據的保存。但如何封裝成一個通用的方法?因爲不同的頁面可能需要保存的字符型字段的個數不一樣。那以上這個方法的參數個數是不定的。如何定義?
找到以下文章(https://blog.csdn.net/never_tears/article/details/78027823)得到啓示。於是完善爲如下方法:
public int execUpdate_private(String sql,String... param) {
Connection con = null;
PreparedStatement psmt = null;
try {
con = getCon();
//獲得預處理對象
psmt = con.prepareStatement(sql);
psmt.setQueryTimeout(20); // set timeout to 20 sec.
//設置實際參數
int length = param.length;
for(int i=0;i<length;i++)
{
psmt.setString(i+1, param[i]);
}
return psmt.executeUpdate();} catch (Exception e) {
e.printStackTrace();} finally {
try {
if( psmt != null ) {
psmt.close();
psmt = null;
}
if( con != null ) {
con.close();
con = null;
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return -1;
}