上述可不可以改成(scanner)从键盘输入名字
时间: 2023-07-31 20:12:34 浏览: 46
当然可以!可以使用`Scanner`类来从键盘获取用户输入的姓名,然后将该姓名传递给SQL语句中的参数。示例代码如下:
```java
// 导入相关的包
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class SearchUserByName {
public static void main(String[] args) {
// 声明数据库连接信息
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf8";
String user = "root";
String password = "123456";
// 从键盘获取需要查找的用户姓名
Scanner scanner = new Scanner(System.in);
System.out.print("请输入需要查找的用户姓名:");
String name = scanner.next();
// 连接数据库
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(url, user, password);
// 编写SQL语句
String sql = "SELECT * FROM user WHERE name = ?";
// 创建PreparedStatement对象
ps = conn.prepareStatement(sql);
ps.setString(1, name);
// 执行SQL语句
rs = ps.executeQuery();
// 输出查询结果
while (rs.next()) {
System.out.println(rs.getString("name") + "\t" + rs.getString("age") + "\t" + rs.getString("address"));
}
} catch (SQLException 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();
}
}
}
}
```
在该示例代码中,我们使用了`Scanner`类来从键盘获取用户输入的姓名,并将该姓名传递给SQL语句中的参数。请注意,该示例代码中的数据库连接信息需要根据实际情况进行修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](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)