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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章