java idbc 根据名字in查询代码
时间: 2024-05-07 15:19:17 浏览: 21
好的,我可以为您提供一个简单的 Java JDBC 根据名字进行模糊匹配查询的例子:
```java
import java.sql.*;
public class QueryByName {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "SELECT * FROM students WHERE name LIKE ?";
try {
// 建立数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
// 创建 PreparedStatement 对象
ps = conn.prepareStatement(sql);
// 设置参数
ps.setString(1, "%in%");
// 执行查询操作
rs = ps.executeQuery();
// 处理结果集
while (rs.next()) {
// 获取每一行数据的各个字段
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// 打印结果
System.out.println("id: " + id + ", name: " + name + ", age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// 关闭 ResultSet 对象
if (rs != null) {
rs.close();
}
// 关闭 PreparedStatement 对象
if (ps != null) {
ps.close();
}
// 关闭 Connection 对象
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
这段代码会在数据库的 `students` 表中模糊匹配(`LIKE` 关键字)名字中包含 "in" 的所有数据,并打印出每一行的 id、name 和 age 字段。请注意,这里的匹配方式可能并不是您想要的,您可以根据实际情况进行修改。另外,这里没有使用一些常见的防 SQL 注入技巧,请不要直接拷贝到生产环境中使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)