JDBC (Java DataBase Connection) 为Java应用程序提供了访问数据库的编程接口
目录
一. JDBC架构
JDBC API:提供应用程序到JDBC管理器连接。Java为连接数据库所提供的接口, JDK自带 java.sql.*
JDBC驱动程序API:支持JDBC管理器到驱动程序连接。数据库厂商提供实现类 mysql-connector-java-5.1.49
javax.sql.*
二. 建立连接
JDBC 应用程序使用以下两个类之一连接到目标数据源:
DriverManager
:这个完全实现的类将应用程序连接到由数据库 URL 指定的数据源。当此类第一次尝试建立连接时,它会自动加载在类路径中找到的任何 JDBC 4.0 驱动程序。请注意,您的应用程序必须手动加载 4.0 版之前的任何 JDBC 驱动程序。
DataSource
:这个接口是首选,DriverManager因为它允许有关底层数据源的详细信息对您的应用程序是透明的。设置对象的DataSource属性以使其代表特定的数据源。
通过DriverManager获取连接
public static void main(String[] args) throws SQLException {
// 获取连接
String url = "jdbc:mysql://localhost:3306/t1";
String user = "root";
String password = "jsw";
Connection connection = DriverManager.getConnection(url, user, password);
}
Mysql Connector/J URL语法
jdbc:mysql://host,failoverhost... :port/database?属性名1=属性值1&属性名2=属性值2...
host:port
是托管数据库的计算机的主机名和端口号。host如果未指定,则和的默认值port分别为 127.0.0.1 和 3306。database
是要连接的数据库的名称。如果未指定,则在没有默认数据库的情况下建立连接。failover
是备用数据库的名称(MySQL Connector/J 支持故障转移)。- propertyName=propertyValue表示一个可选的、以 & 符号分隔的属性列表。这些属性使您能够指示 MySQL Connector/J 执行各种任务。
通过DataSource获取连接
public static void main(String[] args) throws SQLException {
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://localhost:3306/t1?");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("jsw");
Connection connection = dataSource.getConnection();
}
三. JDBC组件
Connection
: 连接组件, 提供统一API建立连接数据库
Statement
: 执行组件, 针对各种执行有不同的实现
ResultSet
: 结果组件, 对结果的抽象, 提供统一的API操作结果数据
Driver
:适配组件,对各个不同的数据库操作进行适配,统一为一套对外一致的API。各个Driver统一由DriverManager进行管理。
1. 执行组件
Statement
: 在运行时使用静态sql语句时很有用, 不能接受参数
PreparedStatement
: 当计划多次使用sql语句时使用, 在运行时接受输入参数
CallableStatement
: 当访问数据库存储过程时使用, 在运行时接受输入参数
Statement
通过connection
的createStatement()
方法创建一个Statement
对象
Statement对象有三种方法
execute(sql)
: 返回布尔类型 true表示执行的是查询语句,false表示执行的是insert,delete,update等等
executeQuery(sql)
: 返回ResultSet结果集
executeUpdate(sql)
: 返回执行影响的行数
public static void main(String[] args) throws SQLException {
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://localhost:3306/t1?characterEncoding=utf-8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("jsw");
Connection connection = dataSource.getConnection();
String sql = "insert into student01 values('zhang', 22)";
Statement statement = connection.createStatement();
// 返回false
boolean execute = statement.execute(sql);
// 返回ResultSet对象, 获取结果集 对select有效
// ResultSet resultSet1 = statement.executeQuery(sql);
// 返回sql语句执行影响的行数 例如:insert update delete
int i1 = statement.executeUpdate(sql);
resultSet.close();
statement.close();
}
PreparedStatement
通过connection
的prepareStatement(sql)
方法返回PreparedStatement
对象
PrepareStatement
对象可以用setString()
方法对sql语句赋参数
Connection connection = dataSource.getConnection();
String sql = "select * from student01 where id = ?";
// 获取PreparedStatement 对象
PreparedStatement statement = connection.prepareStatement(sql);
// 对sql语句赋参数
statement.setString(1, "2");
// 返回结果集
ResultSet resultSet = statement.executeQuery();
// 执行影响的行数
int i = statement.executeUpdate();
System.out.println(i);
resultSet.close();
statement1.close();
CallableStatement
通过connection
的prepareCall(sql)
方法创建CallableStatement
对象
2. 结果组件
ResultSet
数据库查询到的数据放在结果集中, ResultSet
接口表示数据库查询的结果集
查看结果集
// 返回在列中名为columnName的当前行的String值
public int getString(String columnName) throws SQLException
// 返回执行索引当前行中的Sting值,索引从1开始
public int getString(int columnIndex) throws SQLException
public static void main(String[] args) throws SQLException {
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://localhost:3306/t1?characterEncoding=utf-8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("jsw");
Connection connection = dataSource.getConnection();
String sql = "select * from student01";
Statement statement = connection.createStatement();
ResultSet resultSet1 = statement.executeQuery(sql);
// 循环输出结果集
while (resultSet.next()) {
String name = resultSet.getString("name");
String age = resultSet.getString("age");
System.out.println(name + " " + age);
}
resultSet.close();
statement.close();
}
四. 事务
JDBC默认情况下, 在每个sql语句执行完毕之后会自动提交
要启动手动事务支持, 首先关闭自动提交模式, 使用connection
的setAutoCommit(false)
方法, 将自动提交设置为false
完成更改之后使用connection
的commit()
提交, 如果出现异常则回滚更新rollback( )
还可以设置保存点setSavepoint()
try{
// 取消自动提交
conn.setAutoCommit(false);
Savepoint savepoint = conn.setSavepoint();
Statement stmt = conn.createStatement();
String SQL = "INSERT INTO student01 VALUES ('xiao', 22)";
int i = stmt.executeUpdate(SQL);
// 执行成功则提交
conn.commit();
}catch(SQLException se){
// 有异常则回滚
conn.rollback(savepoint);
}