使用步骤:
1.导包,durid1.0.9 jar包
2.定义配置文件,properties文件,名字任意位置也任意,
3.加载文件
4.获得数据库连接池对象 通过DuridDataSourceFactory获得
5.获取连接
代码;
public static void main(String[] args) throws Exception {
//加载文件
Properties properties=new Properties();
//druid.properties文件的位置
InputStream inputStream=Duriddemo1.class.getClassLoader().getResourceAsStream("druid.properties");
//加载
properties.load(inputStream);
//获得数据库连接池对象,通过DruidDataSourceFactory获得
DataSource ds= DruidDataSourceFactory.createDataSource(properties);
//获得连接
Connection connection=ds.getConnection();
System.out.println(connection);
}
使用Druid完成操作:
//完成一个添加操作
public static void main(String[] args) {
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
//获得连接
connection= JDBCUtils.getConnection();
//定义sql 语句 给表coount添加一条记录
String s = "insert into coount values(5,?,?)";
//获得执行sql语句对象
preparedStatement = connection.prepareStatement(s);
//给 ? 赋值
preparedStatement.setString(1,"mimi");
preparedStatement.setDouble(2,3000);
//执行sql语句
int i = preparedStatement.executeUpdate();
System.out.println(i);
} catch (SQLException e) {
e.printStackTrace();
}finally {
//释放资源
JDBCUtils.close(preparedStatement,connection);
}
}