Java原生JDBC(Java Database Connectivity)是Java语言提供的一种与数据库进行交互的标准接口。它允许开发者通过编程方式连接、查询和操作各种类型的数据库。
使用Java原生JDBC,开发者可以通过以下步骤连接数据库、执行SQL语句,并处理查询结果:
- 加载数据库驱动程序:通过
Class.forName("驱动程序类名")
加载数据库所对应的驱动程序。不同的数据库有不同的驱动程序类名。 - 建立数据库连接:使用
DriverManager.getConnection(url, username, password)
方法建立与数据库的连接。其中,url
是数据库的连接字符串,username
和password
是连接数据库所需的用户名和密码。 - 创建一个
Statement
对象:通过connection.createStatement()
方法创建一个Statement
对象,用于执行SQL语句。 - 执行SQL语句:使用
statement.executeUpdate(sql)
方法执行增、删、改操作;使用statement.executeQuery(sql)
方法执行查询操作。其中,sql
是要执行的SQL语句。 - 处理查询结果:对于查询操作,可以使用
ResultSet
对象处理查询结果。可以使用resultSet.next()
方法遍历结果集中的每一行数据,然后通过resultSet.getString(columnName)
或resultSet.getInt(columnName)
等方法获取每一列的数据。 - 关闭连接:使用
connection.close()
方法关闭与数据库的连接。
下面是一个使用Java原生JDBC连接数据库并执行查询的示例代码:
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
// 加载数据库驱动程序
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// 建立数据库连接
connection = DriverManager.getConnection(url, username, password);
// 创建Statement对象
statement = connection.createStatement();
// 执行查询
String sql = "SELECT * FROM mytable";
resultSet = statement.executeQuery(sql);
// 处理查询结果
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("id: " + id + ", name: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
注意:以上示例代码仅用于演示连接数据库和执行查询操作的过程,可能需要根据实际情况进行修改。另外,为了能够运行以上代码,需要将相应的数据库驱动程序添加到项目的Classpath中。