08_傳智播客JDBC_PreparedStatement的應用

package five.base;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import four.utils.utilsSingle;

public class Base {
 
 public static void main(String[] args) throws SQLException {
  read("xuxl");
 }

    static void read(String name) throws SQLException{
       
     PreparedStatement ps = null;
     ResultSet rs = null;
     utilsSingle instance = utilsSingle.getUtilsSingleInstance();

     // 1 創建連接
        Connection connection = instance.getConnection();
        try {
         
            // 2 創建語句
         String sql = "select *from user where name = ?";
         ps = connection.prepareStatement(sql);
         // 向佔位符 設置參數
         ps.setString(1, name);
           
            // 4 執行語句
   // PreparedStatement 繼承於 Statement
   // 所以ps.executeQuery(sql) 不會報錯誤信息
         // 但是執行的是statement的executeQuery
            //rs = ps.executeQuery(sql);
         rs = ps.executeQuery();
            // 5 處理結果
            while (rs.next()) {
                System.out.println(rs.getObject(1)
                        + "/t" + rs.getObject(2)
                        + "/t" + rs.getObject(3)
                        + "/t" + rs.getObject(4)
                        + "/t");
            }
        } finally {
         // 釋放資源 finally
         // PreparedStatement 繼承於 Statement
         // 向上兼容 
   // public void free(Connection connection,
   // Statement statement,
   // ResultSet rs)
         instance.free(connection, ps, rs);
        }
    }
}

發佈了48 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章