Java JDBC 实现教程:从入门到示例
Java 中实现 JDBC 需要以下步骤:
- 导入 JDBC 驱动程序:通过 Class.forName() 方法加载 JDBC 驱动程序,例如:
Class.forName('com.mysql.jdbc.Driver');
- 建立数据库连接:使用 DriverManager.getConnection() 方法建立与数据库的连接,例如:
String url = 'jdbc:mysql://localhost:3306/test';
String user = 'root';
String password = '123456';
Connection conn = DriverManager.getConnection(url, user, password);
- 创建 Statement 对象:通过 Connection.createStatement() 方法创建 Statement 对象,用于执行 SQL 语句,例如:
Statement stmt = conn.createStatement();
- 执行 SQL 语句:通过 Statement 对象执行 SQL 语句,例如:
String sql = 'SELECT * FROM student';
ResultSet rs = stmt.executeQuery(sql);
- 处理查询结果:通过 ResultSet 对象获取查询结果,例如:
while (rs.next()) {
int id = rs.getInt('id');
String name = rs.getString('name');
int age = rs.getInt('age');
System.out.println('id: ' + id + ', name: ' + name + ', age: ' + age);
}
- 释放资源:关闭 ResultSet、Statement 和 Connection 对象,例如:
rs.close();
stmt.close();
conn.close();
完整示例代码:
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
try {
// 导入 JDBC 驱动程序
Class.forName('com.mysql.jdbc.Driver');
// 建立数据库连接
String url = 'jdbc:mysql://localhost:3306/test';
String user = 'root';
String password = '123456';
Connection conn = DriverManager.getConnection(url, user, password);
// 创建 Statement 对象
Statement stmt = conn.createStatement();
// 执行 SQL 语句
String sql = 'SELECT * FROM student';
ResultSet rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
int id = rs.getInt('id');
String name = rs.getString('name');
int age = rs.getInt('age');
System.out.println('id: ' + id + ', name: ' + name + ', age: ' + age);
}
// 释放资源
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
原文地址: https://www.cveoy.top/t/topic/npVB 著作权归作者所有。请勿转载和采集!