给一个JDBC的代码实例
时间: 2024-04-29 09:26:26 浏览: 8
好的,以下是一个简单的 JDBC 代码实例,用于连接 MySQL 数据库并查询数据:
```
import java.sql.*;
public class JDBCDemo {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/mydatabase"; // 数据库连接地址
static final String USER = "username"; // 数据库用户名
static final String PASS = "password"; // 数据库密码
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册 JDBC 驱动器
Class.forName(JDBC_DRIVER);
// 打开一个连接
System.out.println("连接到数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println("实例化Statement对象...");
stmt = conn.createStatement();
String sql = "SELECT id, name, age FROM users";
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.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
// 处理 JDBC 错误
se.printStackTrace();
} catch(Exception e) {
// 处理 Class.forName 错误
e.printStackTrace();
} finally {
// 关闭资源
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
} try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
```
以上代码连接到名为 mydatabase 的 MySQL 数据库,查询用户表中的 id、name 和 age 字段,并将结果输出到控制台。