JDBC
数据库驱动
-
应用程序->JDBC->MySQL驱动->数据库
-
使用JDBC需要java.sql,javax.sql,数据库驱动包
-
- 版本:5.1.48
基本流程
package com.yhr.lesson01;
import java.sql.*;
public class JdbcFirst {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. 加载驱动
Class.forName("com.mysql.jdbc.Driver");//查找并加载指定的类,执行该类的静态代码段
//2. 用户信息和url
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
String username = "root";
String password = "123456";
//3. 连接成功,数据库对象
Connection connection = DriverManager.getConnection(url,username,password);
//4. 执行SQL的对象
Statement statement = connection.createStatement();
//5. 执行SQL,查看返回结果
String sql = "SELECT * FROM users;";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("id=" + resultSet.getObject("id"));
System.out.println("name=" + resultSet.getObject("NAME"));
System.out.println("pwd=" + resultSet.getObject("PASSWORD"));
System.out.println("email=" + resultSet.getObject("email"));
System.out.println("birth=" + resultSet.getObject("birthday"));
}
//6. 释放连接
resultSet.close();
statement.close();
connection.close();
}
}
工具类
-
通过建立properties配置文件和工具类,来简化加载驱动、获取连接、释放资源等问题
-
db.properties
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
username = root
password = 123456
- JdbcUtils.java
package com.yhr.lesson02.utils;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try {
//加载properties
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
//获取参数
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//加载驱动
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//释放资源
public static void release(Connection connection, Statement statement, ResultSet resultSet){
try {
if(resultSet != null){
resultSet.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(statement != null){
statement.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(resultSet != null){
resultSet.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
基本对象
-
DriverManager:
-
DriverManager.registerDriver()
注册驱动- com.mysql.jdbc.Driver的静态代码块自动执行注册
-
DriverManager.getConnection()
获得Connection对象- connection代表数据库:数据库设置自动提交、事务提交、事务回滚等
-
-
URL:
协议://主机地址:端口号/数据库名?参数1&参数2&参数3
- MySQL默认端口号3306,Oracle默认端口号1521
-
ResultSet:封装了所有的查询结果
- 获得指定的数据类型:get***()
- 遍历:beforeFirst(),afterLast(),next(),previous(),absolute(int row)
-
Statement:执行SQL的对象
- 查询:executeQuery(),返回ResultSet
- 更新、插入、删除:executeUpdate(),返回受影响的行数
- execute()执行任何sql,executeBatch()批量执行
- 存在的sql注入漏洞
-
PreparedStatement:预编译,可以防止SQL注入,效率更高
- connection.prepareStatement(sql):使用"?"占位符代替参数
-
例子:
package com.yhr.lesson03;
import com.yhr.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.util.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestInsert {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JdbcUtils.getConnection();
String sql = "INSERT INTO users(id,NAME,PASSWORD,email,birthday) " +
"VALUES (?, ?, ?, ?, ?);";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 4);
preparedStatement.setString(2, "yhr");
preparedStatement.setString(3, "123456");
preparedStatement.setString(4, "yhr@qq.com");
//通过new java.util.Date().getTime()获得时间戳
//转换为java.sql.Date
preparedStatement.setDate(5, new java.sql.Date(new Date().getTime()));
int num = preparedStatement.executeUpdate();
if(num > 0){
System.out.println("插入成功!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(connection, preparedStatement,null);
}
}
}
- 使用‘?‘作为占位符,进行预编译,在用set***(index, x)的方式,设置每一个问号对应的值
- 最后再用execute()执行
- PreparedStatement防止SQL注入的本质,把传递来的参数当做字符,如果存在转义字符,比如‘,直接转义
事务
package com.yhr.lesson04;
import com.yhr.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestTransaction {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = JdbcUtils.getConnection();
//关闭自动提交,开启事务
connection.setAutoCommit(false);
//A减100元
String sql1 = "update jdbcstudy.account set money = money - 100 where name = ‘A‘";
statement = connection.prepareStatement(sql1);
statement.executeUpdate();
//测试回滚
//int x = 1/0;
//B加100元
String sql2 = "update jdbcstudy.account set money = money + 100 where name = ‘B‘";
statement = connection.prepareStatement(sql2);
statement.executeUpdate();
//业务完毕,提交事务
connection.commit();
System.out.println("成功!");
} catch (SQLException throwables) {
// try {
// //如果失败,回滚事务
// //失败时默认回滚,不写也可
// connection.rollback();
// } catch (SQLException e) {
// e.printStackTrace();
// }
throwables.printStackTrace();
} finally {
JdbcUtils.release(connection, statement, resultSet);
}
}
}
数据库连接池
- 池化技术:准备一些预先的资源,过来就连接预先准备好的
- 编写连接池:实现DataSource接口
- 开源数据源实现:DBCP,C3P0,Druid
- 使用数据库连接池后,我们就不需要编写连接数据库的代码了
- 只需重写配置文件和工具类,实现自动连接,使用方法完全相同
DBCP
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名=property;】
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF8
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
- JdbcUtils_DBCP.java
package com.yhr.lesson05.utils;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils_DBCP {
private static DataSource dataSource = null;
static {
try {
//加载properties
InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties properties = new Properties();
properties.load(in);
//创建数据源 工厂模式
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();//从数据源中获取连接
}
//释放资源
public static void release(Connection connection, Statement statement, ResultSet resultSet){
try {
if(resultSet != null){
resultSet.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(statement != null){
statement.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(resultSet != null){
resultSet.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
C3P0
-
c3p0-0.9.5.2.jar和mchange-commons-java-0.2.12.jar,百度云密码c7pr
-
c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--
c3p0的缺省(默认)配置
如果在代码中"ComboPooledDataSource ds=new ComboPooledDataSource();"这样写就表示使用的是c3p0的缺省(默认)-->
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&characterEncoding=utf8&uesSSL=false&serverTimezone=Asia/Shanghai</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquiredIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
</c3p0-config>
- JdbcUtils_C3P0.java
package com.yhr.lesson05.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtils_C3P0 {
private static DataSource dataSource = null;
static {
try {
//xml自动匹配
//创建数据源 工厂模式
dataSource = new ComboPooledDataSource();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();//从数据源中获取连接
}
//释放资源
public static void release(Connection connection, Statement statement, ResultSet resultSet){
try {
if(resultSet != null){
resultSet.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(statement != null){
statement.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(resultSet != null){
resultSet.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}