java學習之PreparedStatement,preparedstatement

來源:互聯網
上載者:User

java學習之PreparedStatement,preparedstatement
     Prepared看到這個單詞,準備的意思,PreparedStatement實則是先行編譯。那麼與Statement又有什麼區別呢?
     PreparedStatemen有這樣的好處:
       1.防止重複編寫多個結構類似的sql語句
  2.沒有拼接字串的煩惱
  3.防止sql注入(拼接字串 會帶來sql注入問題)

  4.sql語句先行編譯在PreparedStatement對象中,效能好

     曾經在學習《牛腩新聞發布系統》的時候,牛老師講過“sql語句注入”這樣的知識,其實到了java還是會存在這樣的問題,PreparedStatement就完美的解決了這樣的問題。

     這樣我就添加一個DRP中的執行個體,來共同學習一下吧。

import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Timestamp;import java.util.ArrayList;import java.util.Date;import java.util.List;
/** * 添加使用者 * @param user */public void addUser(User user) {String sql = "insert into t_user (user_id, user_name, password, contact_tel, email, create_date) " +" values (?, ?, ?, ?, ?, ?)";   //插入新使用者Connection conn = null;//執行個體化PreparedStatement和結果集PreparedStatement pstmt = null;//執行個體化PreparedStatement和結果集try {conn = DbUtil.getConnection();//得到sql語句pstmt = conn.prepareStatement(sql); //先行編譯的作用在這體現出來了。pstmt.setString(1, user.getUserId());   //使用者Idpstmt.setString(2, user.getUserName());  //使用者姓名pstmt.setString(3, user.getPassword());  //使用者密碼pstmt.setString(4, user.getContactTel()); //使用者電話號碼pstmt.setString(5, user.getEmail());//使用者郵箱//pstmt.setTimestamp(6, new Timestamp(System.currentTimeMillis()));pstmt.setTimestamp(6, new Timestamp(new Date().getTime()));pstmt.executeUpdate();}catch(SQLException e) {e.printStackTrace();                   //截取異常的處理}finally {DbUtil.close(pstmt);DbUtil.close(conn);}}
      這隻是一部分代碼,但是很詳細的體現了PreparedStatement的用法。關於底層的應用應該就是固定的知識,當自己見得多了,也就沒有以前的那種心慌了。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.