二、Connection接口
Connection接口概述
Connection接口是Java数据库连接(JDBC)API中的核心接口之一,它代表了一个与数据库的连接。Connection接口提供了与数据库交互的基础,允许执行SQL语句、提交事务等操作。 通过Connection对象,可以执行下列操作:
-
执行SQL语句
-
提交或回滚事务
-
管理事务隔离级别
-
设置自动提交模式
-
关闭连接
// 创建Connection对象通常通过DriverManager类的getConnection方法实现:
Connection conn = DriverManager.getConnection(url,user,password)
url:数据库连接的URL
user:数据库用户名
password:数据库密码
// 执行SQL语句
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM table_name");
stmt.executeUpdate("INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");
// 提交和回滚事务
conn.setAutoCommit(false); // 设置自动提交为 false
conn.commit(); // 提交事务
conn.rollback(); // 回滚事务
// 关闭连接
conn.close();
Java源码:
// Connection接口位于java.sql包中,下面是核心方法
public interface Connection extends Wrapper, AutoCloseable {
Statement createStatement() throws SQLException;
PreparedStatement prepareStatement(String sql) throws SQLException;
CallableStatement prepareCall(String sql) throws SQLException;
String nativeSQL(String sql) throws SQLException;
void setAutoCommit(boolean autoCommit) throws SQLException;
boolean getAutoCommit() throws SQLException;
void commit() throws SQLException;
void rollback() throws SQLException;
void close() throws SQLException;
boolean isClosed() throws SQLException;
DatabaseMetaData getMetaData() throws SQLException;
void setReadOnly(boolean readOnly) throws SQLException;
boolean isReadOnly() throws SQLException;
void setCatalog(String catalog) throws SQLException;
String getCatalog() throws SQLException;
void setTransactionIsolation(int level) throws SQLException;
int getTransactionIsolation() throws SQLException;
SQLWarning getWarnings() throws SQLException;
void clearWarnings() throws SQLException;
Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException;
PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
Map<String, Class<?>> getTypeMap() throws SQLException;
void setTypeMap(Map<String, Class<?>> map) throws SQLException;
// 更多方法...
}
源码中核心方法的解析:
-
createStatement()
-
作用:创建了一个Statement对象,用于执行SQL语句
-
抛出异常:SQLException
-
-
prepareStatement(String sql)
-
作用:创建一个预编译的PreparedStatement对象,用于执行SQL语句
-
参数:sql是要执行的SQL语句
-
抛出异常:SQLException
-
-
prepareCall(String sql)
-
作用:创建一个CallableStatement,用于执行存储过程或函数
-
参数:sql是要执行的SQL语句
-
抛出异常:SQLException
-
-
setAutoCommit(boolean autoCommit)
-
作用:设置自动提交模式
-
参数:autoCommit表示是否开启自动提交
-
抛出异常:SQLException
-
-
commit()
-
作用:提交当前的事务
-
抛出异常:SQLException
-
-
rollback()
-
作用:回滚当前事务
-
抛出异常:SQLException
-
-
close()
-
关闭当前连接
-
抛出异常:SQLException
-
-
isClosed()
-
作用:检查连接是否已关闭
-
返回值:boolean,表示连接是否已关闭
-
抛出异常:SQLException
-
-
setTransactionIsolation(int level)
-
作用:设置事务隔离级别
-
参数:level是事务隔离级别的常量
-
抛出异常:SQLException
-