概念
JDBC是是Java数据库连接技术的简称,提供连接数据库的能力
JDBC API
Java 作为目前世界上最流行的高级开发语言,当然不可能考虑去实现各种数据库的连接与操作。但 Java 语言的开发者对数据库的连接与操作提供了相关的接口,供各大数据库厂商去实现。这些接口位于java.sql 包中
Driver
java.sql.Driver:数据库厂商提供的JDBC驱动包中必须包含该接口的实现,该接口中就包含连接数,该接口中就包含连接数
Connection connect(String url, java.util.Properties info) throws SQLException;
DriverManager
java.sql.DriverManager:数据库厂商的提供的 JDBC 驱动交给 DriverManager 来管理,
DriverManager** 主要负责获取数据库连接对象 Connection**
//通过给定的账号、密码和数据库地址获取一个连接
public static Connection getConnection(String url, String user, String password) throws SQLException
Connection
java.sql.Connection :连接接口,数据库厂商提供的 JDBC 驱动包中必须包含该接口的实现,该接口主要提供与数据库的交互功能
//创建一个SQL语句执行对象
Statement createStatement() throws SQLException;//创建一个预处理SQL语句执行对象
PreparedStatement prepareStatement(String sql) throws SQLException;//创建一个存储过程SQL语句执行对象
CallableStatement prepareCall(String sql) throws SQLException;//设置该连接上的所有操作是否执行自动提交
void setAutoCommit(boolean autoCommit) throws SQLException;//提交该连接上至上次提交以来所作出的所有更改
void commit() throws SQLException;//回滚事务,数据库回滚到原来的状态
void rollback() throws SQLException;//关闭连接
void close() throws SQLException;//设置事务隔离级别
void setTransactionIsolation(int level) throws SQLException;
Statement
java.sql.statement:SQL语句执行接口,SQL语句执行接口,数据库厂商提供的 JDBC 驱动包中必须包含该接口的实现,该接口主要提供执行 SQL 语句的功能
//执行查询,得到一个结果集
ResultSet executeQuery(String sql) throws SQLException;
//执行更新,得到受影响的行数
int executeUpdate(String sql) throws SQLException;
//关闭SQL语句执行器
void close() throws SQLException;
//将SQL语句添加到批处理执行SQL列表中
void addBatch( String sql ) throws SQLException;
//执行批处理,返回列表中每一条SQL语句的执行结果
int[] executeBatch() throws SQLException;
ResultSet
java.sql.ResultSet :查询结果集接口,数据库厂商提供的 JDBC 驱动包中必须包含该接口的实现,该接口主要提供查询结果的获取功能
//光标从当前位置(默认位置位为0)向前移动一行,如果存在数据,则返回true,否则返回false
boolean next() throws SQLException;
//关闭结果集
void close() throws SQLException;
//获取指定列的字符串值
String getString(int columnIndex) throws SQLException;
//获取指定列的布尔值
boolean getBoolean(int columnIndex) throws SQLException;
//获取指定列的整数值
int getInt(Sting columnName) throws SQLException;
//获取指定列的对象
Object getObject(int columnIndex, Class type) throws SQLException;
//获取结果集元数据:查询结果的列名称、列数量、列别名等等
ResultSetMetaData getMetaData() throws SQLException;
//光标从当前位置(默认位置位为0)向后移动一行,如果存在数据,则返回true,否则返回false
boolean previous() throws SQLException;
JDCB操作步骤
引入驱动包
新建工程后,将mysql-connectionor-java.jar引入工程中
加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
获取连接
Connection connection = DriverManager.getConnection(url, username, password);
创建SQL语句执行器
Statement statement = connection.createStatement();
执行SQL语句
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){//获取列信息
}//更新
int affectedRows = statement.executeUpdate();
释放资源
rs.close();
statement.close();
connection.close();