jdbc访问数据库实现查询user表信息,列:id name sex
时间: 2024-02-24 21:53:18 浏览: 31
以下是使用 JDBC 访问数据库实现查询 user 表信息的示例代码,查询的列为 id、name 和 sex:
```java
import java.sql.*;
public class UserDAO {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载 JDBC 驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库连接对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name", "username", "password");
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行查询语句
String sql = "SELECT id, name, sex FROM user";
rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String sex = rs.getString("sex");
System.out.println("id: " + id + ", name: " + name + ", sex: " + sex);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
需要注意的是,上述代码中的 db_name、username 和 password 需要替换为实际的数据库名、用户名和密码。另外,为了提高代码的可维护性和可测试性,应该将 JDBC 代码封装在 DAO 层中,而不是直接在 JSP 中编写。