请使用JDBC技术实现对t_user表(字段:id,name,gender,age,birthday)中“张”姓员工的查询。
时间: 2024-03-03 16:48:05 浏览: 93
好的,以下是使用JDBC技术实现对t_user表中“张”姓员工的查询的示例代码:
```java
import java.sql.*;
public class Main {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 创建数据库连接
String url = "jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// SQL语句
String sql = "SELECT id, name, gender, age, birthday FROM t_user WHERE name LIKE '张%'";
// 创建PreparedStatement对象
ps = conn.prepareStatement(sql);
// 执行查询
rs = ps.executeQuery();
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
int age = rs.getInt("age");
Date birthday = rs.getDate("birthday");
System.out.println("id:" + id + ", name:" + name + ", gender:" + gender + ", age:" + age + ", birthday:" + birthday);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,我们首先使用Class.forName()方法加载MySQL的JDBC驱动,然后通过DriverManager.getConnection()方法创建数据库连接。接着,我们使用PreparedStatement对象执行SQL查询语句,并将结果集通过while循环进行遍历,最后释放资源。
需要注意的是,上面的代码中的SQL语句中使用了LIKE操作符来查询“张”姓员工,其中“%”表示通配符,可以匹配任意字符。
阅读全文
相关推荐















