jdbc示例
时间: 2023-07-07 17:08:31 浏览: 43
以下是一个简单的 JDBC 示例,它连接到 MySQL 数据库并从一个名为 `employees` 的表中检索数据:
```java
import java.sql.*;
public class JdbcExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/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("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT id, first_name, last_name FROM employees";
ResultSet rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String first = rs.getString("first_name");
String last = rs.getString("last_name");
System.out.print("ID: " + id);
System.out.print(", First Name: " + first);
System.out.println(", Last Name: " + last);
}
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!");
}
}
```
请注意,此示例需要 MySQL JDBC 驱动程序。您需要将 MySQL JDBC 驱动程序 JAR 文件添加到您的项目中。