1. 程式人生 > 實用技巧 >MYSQL 之 JDBC(五): 增刪改查(三)PreparedStatement

MYSQL 之 JDBC(五): 增刪改查(三)PreparedStatement

是Statement的子介面,可以傳入帶佔位符的sql語句,並且提供了補充佔位符變數的方法。

使用Statement需要進行拼寫SQL語句,很辛苦,很容易出錯。

引號的問題處理很複雜,不利於維護。

可以有效的禁止sql注入。(通過使用者輸入非法的sql命令)

程式碼的可讀性和可維護性,最大可能的提高效能(批量插入)

程式碼測試

public void testPreparedStatement() {
    Connection connection = null;
    PreparedStatement ps = null;

    try {
        connection 
= JDBCTools.getConnection(); String sql = "insert into t_user (id, username, pwd, regTime, lastLoginTime) values(?,?,?,?,?)"; ps = connection.prepareStatement(sql); ps.setInt(1, 2); ps.setString(2, "狗賊"); ps.setString(3, "123456"); ps.setDate(4, new Date(System.currentTimeMillis())); ps.setTimestamp(
5, new Timestamp(System.currentTimeMillis())); ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { JDBCTools.release(ps, connection); } }


————————————————

版權宣告:本文為CSDN博主「李英俊小朋友」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/qq_21579045/article/details/105386353