数据库连接池Druid

package study.datasoure;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * 步骤:
 * 1、导入jar包:druid-1.0.9.jar
 * 2、定义配置文件:
 *      properties 形式的配置文件
 *      配置文件可以是任意名称,可以放在任意目录下
 * 3、获取数据库连接池对象:
 *    通过工厂类来获取:DruidDataSorceFactory
 * 4、获取连接:
 *    getConnection()
 *
 * 5、操作数据库
 *
 */
public class Druid {
    public static void main(String[] args) throws Exception {
        //1、获取连接池对象
        Properties pro = new Properties();
        InputStream is = Druid.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);
        DataSource ds = DruidDataSourceFactory.createDataSource(pro);
        //2、获取连对象
        Connection conn = ds.getConnection();

        //3、使用
        //定义查询语句 使用?占位符
        String select = "select * from emp where id = ?";

        //获取执行SQL对象
        PreparedStatement pstm = conn.prepareStatement(select);
        //占位符参数
        pstm.setInt(1,1002);
        //执行查询语句
        ResultSet res = pstm.executeQuery();

        while (res.next()){
            System.out.println(res.getInt("id"));
            System.out.println(res.getString("ename"));
            System.out.println(res.getInt("job_id"));
            System.out.println(res.getInt("mgr"));
            System.out.println(res.getDate("joindate"));
            System.out.println(res.getDouble("salary"));
            System.out.println(res.getDouble("bonus"));
            System.out.println(res.getInt("dept_id"));
        }
    }
}

druid.png

仅有一条评论

添加新评论