PreparedStatement的基本操作步骤

1、  创建PreparedStatement对象:

PreparedStatement pre = null;

2、通过数据库连接获取PreparedStatement对象:

Pre = con.preparedStatement(sql);

3、为pre设置操作条件:

Pre.setObject();

4、执行对数据库的操作:

A、增加记录、删除记录、更新记录

Pre.executeUpdate();返回操作记录条数

D、查询记录

Pre.executeQuery();返回ResultSet类型的结果集

ResultSet集合类型

1、  基本处理方法

Next()//指向下一个记录,存在就返回true、不存在就返回true

GetXXX(columnnumber/columnname)//XXX表示数据类型,参数为列数和列名,返回每一列的数据

2、  GetMetaData()//返回结果集的基本信息,返回类型为ResultSetMetaData

ResultSetMetaData

getColumnCount()//返回列数

getColumnName(int index)//返回列名

getColumnType(int index)//返回列类型

实例操作

package StatementTest;

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

import connection.ConnectionPool;
import connection.ConnectionProvider;

public class PreparedStatementTest {
/*创建连接池+DataSource操作*/
    private  static ConnectionPool connectionPool;

/*创建线程池+ThreadLocal<T>操作*/
    
    //创建线程池
    private static ThreadLocal<Connection> conWrapper = new ThreadLocal<Connection>();
    //打开连接
    private Connection getConnection() throws Exception{
        Connection con = connectionPool.getConnection();
        if(con != null || !con.isClosed()){
            return con;
        }
        //从线程池中获取数据库连接
        con = connectionPool.getConnection();
        if(con == null){
            throw new SQLException("无法获取数据库连接"); 
        }
        //对新创建的数据库连接放到线程池中
        conWrapper.set(con);
        return con;
    }
    //关闭连接
    private void closeConnection() throws SQLException{
        //从线程池中获取连接池
        Connection con = conWrapper.get();
        if(con != null){
            con.close();
        }
        conWrapper.remove();
    }
//创建PreparedStatement的测试+返回结果保存在ResultSet中
public static void main(String[] args) throws Exception{
    PreparedStatement pre = null;
    PreparedStatementTest pretest = new PreparedStatementTest();
    Connection con = pretest.getConnection();
    String sql = "select * from student where age = ?";
    pre = con.prepareStatement(sql);
    int x = 23;
    pre.setObject(0, x);
    ResultSet res = pre.executeQuery();
    ResultSetMetaData rsmd = res.getMetaData();
    int count = rsmd.getColumnCount();
    while(res.next()){
        int age = res.getInt("age");
        for(int i=1;i<=count;i++){
            String name = rsmd.getColumnName(i);
        }
    }
}
}