jar包和配置文件:st0b
一.步骤
1.导入jar包和配置文件
如下图:
2.项目结构
3.项目代码
druid.java
package druid;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
public class druid {
public static void main(String[] args) {
//1.导入jar包和配置文件
//2.加载配置文件
Properties properties = new Properties();
InputStream inputStream = druid.class.getClassLoader().getResourceAsStream("druid.properties");
System.out.println(inputStream);
PreparedStatement preparedStatement1 = null;
PreparedStatement preparedStatement2 = null;
Connection connection = null;
try {
properties.load(inputStream);
//3.获取连接池对象
DataSource ds = DruidDataSourceFactory.createDataSource(properties);
//4.获取连接
connection = ds.getConnection();
System.out.println(connection);
connection.setAutoCommit(false);//创建事务
String sql1 = "update account set balance = balance - ? where id = ?";
//2.2 李四 + 500
String sql2 = "update account set balance = balance + ? where id = ?";
//3.获取执行sql对象
preparedStatement1 = connection.prepareStatement(sql1);
preparedStatement2 = connection.prepareStatement(sql2);
//4. 设置参数
preparedStatement1.setDouble(1, 500);
preparedStatement1.setInt(2, 1);
preparedStatement2.setDouble(1, 500);
preparedStatement2.setInt(2, 2);
//5.执行sql
preparedStatement1.executeUpdate();
preparedStatement2.executeUpdate();
connection.commit();//提交事务
} catch (Exception e) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
} finally {
try {
connection.close();
preparedStatement1.close();
preparedStatement2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
配置文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/li
username=root
password=517818li
#初始化连接数
initialSize=5
#最大连接数
maxActive=10
#最大等待时间
maxWait=3000
4出现错误
新版mysql已弃用com.mysql.jdbc.Driver
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
四月 19, 2020 12:31:57 下午 com.alibaba.druid.pool.vendor.MySqlValidConnectionChecker warn
警告: Cannot resolve com.mysq.jdbc.Connection.ping method. Will use 'SELECT 1' instead.
5.解决办法
修改配置文件
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/li
username=root
password=517818li
#初始化连接数
initialSize=5
#最大连接数
maxActive=10
#最大等待时间
maxWait=3000