JDBC
JDBC(java Data Base Connectivity),java数据库连接,专门用来连接数据库的。
JDBC连接MySQL
url:jdbc:mysql://主机名称:mysql服务端口号/数据库名称
user:用户名
password:密码
driveName :com.mysql.jdbc.Driver(驱动)
@Test
public void testConnection() throws Exception {
//连接数据库的四大要素
String url = "jdbc:mysql://localhost:3306/zxc";
String user = "root";
String password = "root";
//8.0版本后改为com.mysql.cj.jdbc.Driver
String driveName = "com.mysql.jdbc.Driver";
//连接一
//实例化Driver
Class<?> clazz = Class.forName(driveName);
Driver driver = (Driver) clazz.newInstance();
//注册驱动
DriverManager.registerDriver(driver);
//获取连接
DriverManager.getConnection(url, user, password);
//连接二
//加载驱动,会在第一次使用这个Class时将,会driveName加载到内存,
// 引入驱动的Drive类会自动执行它的方法。
Class.forName(driveName);
DriverManager.getConnection(url,user,password);
//连接三
//Java程序启动时,在引入的驱动里找MEAT-INF.service.java.sqlDrover,
// 如果能找到,就会将其加载到内存,自动注册
DriverManager.getConnection(url,user,password);
}
编写SQL语句
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
//建立事务
Statement statement = connection.createStatement();
//sql查询executeQuery sql增删改execute
resultSet resultSet = statement.executeQuery(sql);
预编译SQL
使用prepared Statement 可以解决SQL注入,比statement更加方便
Connection connection = DBUtil.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
PreparedStatement preparedStatement.setInt(1,id);;
ResultSet resultSet = preparedStatement.executeQuery();
数据库连接池
一开始就在内存中开辟一块空间(集合),先往池子里面放置多个连接对象。后面需要连接的话,直接从池子里面取。不需要自己创建连接。使用完毕之后归还连接确保连接对象能循环利用。减少了性能的消耗,不需要再关闭连接。使用前要引入相应的jar包。
c3p0、BBCP现在基本不用
Druid(德鲁伊)
/*
*德鲁伊配置文件
* url=jdbc:mysql://localhost:3306/zxc
* username=root
* password=root
* driverClassName=com.mysql.jdbc.Driver
* initialSize=10
* maxActive=20
* maxWait=1000
* filters=wall
* */
public static Connection getConnection() {
//拿到dataSource,用map存
Map<String, String> prop = new HashMap<>();
prop.put("url", "jdbc:mysql://localhost:3306/zxc");
prop.put("username", "root");
prop.put("password", "root");
prop.put("driverClassName", "com.mysql.jdbc.Driver");
DataSource dataSource = null;
try {
dataSource = DruidDataSourceFactory.createDataSource(prop);
} catch (Exception e) {
e.printStackTrace();
}
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
Hikari(光)
private static DataSource dataSource;
static {
try {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/zxc");
hikariConfig.setUsername("root");
hikariConfig.setPassword("root");
hikariConfig.setDriverClassName("com.mysql.jdbc.Driver");
dataSource = new HikariDataSource(hikariConfig);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}