JDBC常用接口和类简介
- DriverManager用于管理JDBC驱动的服务类。程序中使用该类的主要作用是获取Connection对象
- public static Connection getConnection(String url, String user, String password) throws SQLException: 获取url对应数据库的连接。
- Connection:代表数据库连接对象
- Statement createStatement() throws SQLException:返回一个Statement对象
- PreparedStatement prepareStatement(String sql) throws
SQLException:返回一个PreparedStatement对象 - CallableStatement prepareCall(String sql) throws SQLException:用于调用存储过程
- Savepoint setSavepoint() throws SQLException:用于控制事务,创建一个保存点
- Savepoint setSavepoint(String name) throws SQLException:用于控制事务,以指定名字来创建一个保存点
- void setTransactionIsolation(int level) throws SQLException:用于控制事务,设置事务的隔离级别
- void rollback() throws SQLException:回滚事务
- void rollback(Savepoint savepoint) throws SQLException:将事务回滚到指定的保存点
- void setAutoCommit(boolean autoCommit) throws SQLException:关闭自动提交,打开事务
- void commit() throws SQLException:提交事务
- Statement:用于执行SQL语句的工具接口
- ResultSet executeQuery(String sql) throws SQLException:执行查询语句,并返回查询结果
- int executeUpdate(String sql) throws SQLException:执行DML语句(数据操作语言),并返回受影响的行数;也可以执行DDL(数据定义语言),只返回0
- boolean execute(String sql) throws SQLException:执行任何SQL语句。如果执行后第一个结果为ResultSet对象,则返回TRUE;如果执行后第一个结果为受影响的行数或没有任何结果,则返回FALSE
- PreparedStatement:预编译的Statement对象
- void setXxx(int parameterIndex, Xxx value) throws SQLException:设置参数的值。index从1开始
- ResultSet:结果集对象
- void close() throws SQLException:释放ResultSet对象
- boolean absolute( int row ) throws SQLException:将结果集移动到第几行,如果row是负数,则移动到倒数第几行。如果移动后的记录指针指向一条有效的记录,则该方法返回TRUE
- void beforeFirst() throws SQLException:将ResultSet的记录指针定位到首行之前,这是ResultSet结果集记录指针的初始状态
- boolean first() throws SQLException:将ResultSet的记录指针定位到首行。如果移动后的记录指针指向一条有效的记录,则该方法返回TRUE
- boolean previous() throws SQLException:将ResultSet的记录指针定位到上一行。如果移动后的记录指针指向一条有效的记录,则该方法返回TRUE
- boolean last() throws SQLException:将ResultSet的记录指针定位到最后一行。如果移动后的记录指针指向一条有效的记录,则该方法返回TRUE
- boolean afterLast() throws SQLException:将ResultSet的记录指针定位到最后一行之后。
JDBC编程步骤
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/test", "root", "123456");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from user");
System.out.println("ID \t 用户名 \t 密码 ");
while (rs.next()) {
int id = rs.getInt(1);
String username = rs.getString(2);
String pwd = rs.getString(3);
System.out.println(id + "\t" + username + "\t" + pwd);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}