在Java语言中,数据库JDBC实现连接操作步骤: [1]加载指定数据库类型的JDBC驱动 [2]构建用于连接数据库的Connection对象 [3]使用Connection构建Statement对象 [4]使用Statement对象执行SQL数据库操作 [5]使用ResultSet对象处理数据查询结果 [6]关闭数据库连接对象 按照如下代码进行完成:
时间: 2023-11-25 13:08:25 浏览: 28
这是Java语言中使用JDBC实现连接操作的代码:
```
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载指定数据库类型的JDBC驱动
Class.forName("com.mysql.jdbc.Driver");
// 构建用于连接数据库的Connection对象
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "password";
con = DriverManager.getConnection(url, user, password);
// 使用Connection构建Statement对象
stmt = con.createStatement();
// 使用Statement对象执行SQL数据库操作
String sql = "SELECT * FROM users";
rs = stmt.executeQuery(sql);
// 使用ResultSet对象处理数据查询结果
while (rs.next()) {
System.out.println(rs.getString("name") + " " + rs.getString("email"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭数据库连接对象
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```