Java JDBC基础
Java JDBC基础
Java JDBC(Java Database Connectivity)是Java语言中用于与关系型数据库进行交互的标准API。使用JDBC,Java程序可以访问任何符合JDBC标准的关系型数据库,如MySQL,Oracle,SQL Server等。
JDBC架构
JDBC架构包括两个组件:JDBC API 和 JDBC驱动程序。JDBC API提供了一组接口和类,用于在Java应用程序中与数据库进行交互。JDBC驱动程序实现了JDBC API的接口,以便Java程序可以使用它们与特定的数据库进行通信。
JDBC API
JDBC API包括以下核心接口和类:
-
DriverManager
: jdbc驱动程序,在MySQL5版本后可以省略不写;DriverManager
是Java JDBC API的一部分,用于管理注册的 JDBC 驱动程序。使用DriverManager
,您可以:- 注册 JDBC 驱动程序
- 获取 Connection 对象
- 获取 Driver 信息
以下是一些常用的
DriverManager
方法:void registerDriver(Driver driver)
:将指定的Driver
对象注册到DriverManager
中。Connection getConnection(String url, String user, String password)
:使用给定的URL、用户名和密码获取Connection
对象。Connection getConnection(String url)
:使用给定的URL获取Connection
对象。void setLoginTimeout(int seconds)
:设置连接超时时间(以秒为单位)。void setLogWriter(PrintWriter out)
:设置日志输出流。
以下是一个使用
DriverManager
获取Connection
对象的简单示例:import java.sql.*; public class DriverManagerExample { public static void main(String[] args) { try { // 加载JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 获取Connection对象 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "password"); // 关闭连接 conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
在上面的示例中,我们使用
DriverManager.getConnection
方法获取了一个Connection
对象,该对象表示与数据库之间的连接。请注意,我们必须在使用DriverManager.getConnection
方法之前加载 JDBC 驱动程序。 -
Connection:用于创建与数据库之间的连接。
Connection
接口用于创建与数据库之间的连接。使用Connection
对象,您可以执行 SQL 语句,并处理执行结果。下面是一些Connection
对象的常用方法:void close()
:关闭连接。Statement createStatement()
:创建Statement
对象,用于执行静态 SQL 语句。PreparedStatement prepareStatement(String sql)
:创建PreparedStatement
对象,用于执行动态 SQL 语句。CallableStatement prepareCall(String sql)
:创建CallableStatement
对象,用于调用存储过程。void setAutoCommit(boolean autoCommit)
:设置是否自动提交事务。void commit()
:提交事务。void rollback()
:回滚事务。
下面是一个使用
Connection
对象创建与数据库之间连接的简单示例:import java.sql.*; public class ConnectionExample { public static void main(String[] args) { try { // 加载 JDBC 驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 创建数据库连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "password"); // 执行 SQL 语句 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM employees"); while (rs.next()) { System.out.println(rs.getString("first_name") + " " + rs.getString("last_name")); } // 关闭连接 rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
在上面的示例中,我们使用
DriverManager.getConnection
方法创建了一个Connection
对象,该对象表示与数据库之间的连接。然后,我们使用Statement
对象执行了一个简单的SELECT
语句,并使用ResultSet
对象遍历结果集。最后,我们关闭了连接、语句和结果集对象。请注意,上面的示例代码仅用于演示目的。在实际应用程序中,您需要考虑使用
PreparedStatement
对象来执行 SQL 语句,以防止 SQL 注入攻击。 -
Statement:用于执行SQL语句。
JDBC中的Statement接口用于执行SQL语句。与PreparedStatement不同,Statement不支持参数化查询,也不支持批量操作。
以下是一些常用的Statement方法:
void execute(String sql)
:执行给定的SQL语句,可以是任何类型的SQL语句。ResultSet executeQuery(String sql)
:执行SELECT语句,并返回代表结果集的ResultSet对象。int executeUpdate(String sql)
:执行INSERT、UPDATE或DELETE语句,并返回受影响的行数。
以下是一个使用Statement对象执行SQL语句的简单示例:
import java.sql.*; public class StatementExample { public static void main(String[] args) { try { // 加载JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 创建数据库连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "password"); // 创建Statement对象 Statement stmt = conn.createStatement(); // 执行SQL语句 int rows = stmt.executeUpdate("INSERT INTO employees (first_name, last_name) VALUES ('John', 'Doe')"); System.out.println(rows + " rows affected"); // 关闭连接和语句对象 stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
在上面的示例中,我们使用
Connection.createStatement
方法创建了一个Statement对象,该对象用于执行SQL语句。然后,我们使用Statement.executeUpdate
方法执行了一个INSERT语句,并使用返回的受影响的行数输出消息。最后,我们关闭了连接和语句对象。请注意,上述示例代码仅用于演示目的。在实际应用程序中,您需要考虑使用PreparedStatement对象来执行SQL语句,以防止SQL注入攻击。
-
PreparedStatement:与Statement类似,但是可以通过占位符设置参数。
-
PreparedStatement:与Statement类似,但是可以通过占位符设置参数。
PreparedStatement
接口与Statement
类似,但它可以使用占位符设置参数。这使得它更适合执行参数化查询,以防止SQL注入攻击。以下是一些
PreparedStatement
对象的常用方法:void setInt(int parameterIndex, int x)
:将指定的整数设置为指定位置的参数。void setString(int parameterIndex, String x)
:将指定的字符串设置为指定位置的参数。void setBoolean(int parameterIndex, boolean x)
:将指定的布尔值设置为指定位置的参数。void setDouble(int parameterIndex, double x)
:将指定的双精度浮点数设置为指定位置的参数。ResultSet executeQuery()
:执行SELECT语句,并返回代表结果集的ResultSet
对象。int executeUpdate()
:执行INSERT、UPDATE或DELETE语句,并返回受影响的行数。
以下是一个使用
PreparedStatement
对象执行SQL语句的简单示例:import java.sql.*; public class PreparedStatementExample { public static void main(String[] args) { try { // 加载JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 创建数据库连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "password"); // 创建PreparedStatement对象 PreparedStatement pstmt = conn.prepareStatement("INSERT INTO employees (first_name, last_name) VALUES (?, ?)"); // 设置参数 pstmt.setString(1, "John"); pstmt.setString(2, "Doe"); // 执行SQL语句 int rows = pstmt.executeUpdate(); System.out.println(rows + " rows affected"); // 关闭连接和PreparedStatement对象 pstmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
在上面的示例中,我们使用
Connection.prepareStatement
方法创建了一个PreparedStatement
对象,该对象用于执行SQL语句。然后,我们使用PreparedStatement.setString
方法设置了两个参数,以便它们可以作为占位符出现在SQL语句中。最后,我们使用PreparedStatement.executeUpdate
方法执行了一个INSERT语句,并使用返回的受影响的行数输出消息。最后,我们关闭了连接和PreparedStatement对象。请注意,上述示例代码仅用于演示目的。在实际应用程序中,您需要考虑使用PreparedStatement对象来执行SQL语句,以防止SQL注入攻击。
-
-
CallableStatement:用于调用存储过程。
CallableStatement
接口用于调用存储过程。存储过程是一组预定义的 SQL 语句,可以像函数一样在数据库中执行。存储过程通常用于执行复杂的数据操作,例如在多个表之间进行联接和更新。以下是一些CallableStatement
对象的常用方法:void setInt(int parameterIndex, int x)
:将指定的整数设置为指定位置的参数。void setString(int parameterIndex, String x)
:将指定的字符串设置为指定位置的参数。void setBoolean(int parameterIndex, boolean x)
:将指定的布尔值设置为指定位置的参数。void setDouble(int parameterIndex, double x)
:将指定的双精度浮点数设置为指定位置的参数。void registerOutParameter(int parameterIndex, int sqlType)
:注册一个输出参数。ResultSet executeQuery()
:执行SELECT语句,并返回代表结果集的ResultSet
对象。int executeUpdate()
:执行INSERT、UPDATE或DELETE语句,并返回受影响的行数。void execute()
:执行存储过程。
以下是一个使用
CallableStatement
对象调用存储过程的简单示例:import java.sql.*; public class CallableStatementExample { public static void main(String[] args) { try { // 加载 JDBC 驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 创建数据库连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "password"); // 创建 CallableStatement 对象 CallableStatement cstmt = conn.prepareCall("{CALL get_employee_name(?, ?)}"); // 设置输入参数 cstmt.setInt(1, 100); // 注册输出参数 cstmt.registerOutParameter(2, Types.VARCHAR); // 执行存储过程 cstmt.execute(); // 获取输出参数 String name = cstmt.getString(2); System.out.println("Employee name: " + name); // 关闭连接和 CallableStatement 对象 cstmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
在上面的示例中,我们使用
Connection.prepareCall
方法创建了一个CallableStatement
对象,该对象用于调用存储过程。然后,我们使用CallableStatement.setInt
方法设置了一个输入参数。接下来,我们使用CallableStatement.registerOutParameter
方法注册了一个输出参数。最后,我们使用CallableStatement.execute
方法执行存储过程,并使用CallableStatement.getString
方法获取输出参数的值。最后,我们关闭了连接和CallableStatement
对象。请注意,上述示例代码仅用于演示目的。在实际应用程序中,您需要考虑使用
PreparedStatement
对象来执行SQL语句,以防止SQL注入攻击。 -
ResultSet:用于获取查询结果。
ResultSet
对象用于获取查询结果。它包含指向结果集的游标,并提供了一组用于检索和操作数据的方法。以下是一些
ResultSet
对象的常用方法:boolean next()
:将游标移动到结果集的下一行。如果有更多的行,则返回true。否则,返回false。void close()
:关闭结果集。int getInt(int columnIndex)
:返回指定列的值作为int。String getString(int columnIndex)
:返回指定列的值作为String。boolean getBoolean(int columnIndex)
:返回指定列的值作为boolean。double getDouble(int columnIndex)
:返回指定列的值作为double。
以下是一个使用
ResultSet
对象遍历结果集的简单示例:import java.sql.*; public class ResultSetExample { public static void main(String[] args) { try { // 加载JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 创建数据库连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "password"); // 执行SQL语句 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM employees"); // 遍历结果集 while (rs.next()) { System.out.println(rs.getString("first_name") + " " + rs.getString("last_name")); } // 关闭连接和语句对象 rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
在上面的示例中,我们使用
ResultSet.next
方法遍历结果集,并使用ResultSet.getString
方法获取first_name
和last_name
列的值。最后,我们关闭了连接、语句和结果集对象。
JDBC驱动程序
JDBC驱动程序是JDBC API的实现,用于与特定的数据库进行通信。JDBC驱动程序通常由数据库供应商提供,因为它们需要了解特定数据库的细节。
JDBC驱动程序通常分为四种类型:
- JDBC-ODBC桥接器驱动程序
- 原生API驱动程序
- 网络协议驱动程序
- JDBC类型4驱动程序
JDBC使用步骤
JDBC使用步骤如下:
- 加载JDBC驱动程序。
- 创建数据库连接。
- 创建Statement,PreparedStatement或CallableStatement对象。
- 执行SQL语句或调用存储过程。
- 处理结果集。
- 关闭连接和语句对象。
结论
Java JDBC是与关系型数据库进行交互的标准API。JDBC架构由JDBC API和JDBC驱动程序组成。JDBC API包括Connection,Statement,PreparedStatement,CallableStatement和ResultSet等核心接口和类。JDBC驱动程序实现了JDBC API的接口,以便Java程序可以使用它们与特定的数据库进行通信。JDBC使用步骤包括加载JDBC驱动程序,创建数据库连接,执行SQL语句或调用存储过程,处理结果集以及关闭连接和语句对象。