实现模糊查询(以“查哪个用户的密码中的第二个字符为‘a’为例)...... import java.sql.*; public class DBUtil { //
import java.sql.*;
public class DBUtil {
//静态代码块在类加载时执行,并且只执行一次
static {
try {
Class.forName("com.Mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private DBUtil(){
}
//因为此方法是被调用的方法,所以出现异常直接上抛就行
public static Connection getConnection () throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode"
, "root", "888");
}
public static void close(Connection connection,Statement statement,ResultSet resultSet){
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
import java.sql.*;
public class JDBCTest03 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
//注册+获取连接
connection = DBUtil.getConnection();
//获取预编译的数据库操作对象
String sql = "select loginPwd from t_user where loginPwd like ?";
ps = connection.prepareStatement(sql);
ps.setString(1,"_a%");
//执行sql语句
resultSet = ps.executeQuery();
//处理查询结果集
while (resultSet.next()){
System.out.println(resultSet.getString("loginPwd"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭资源
DBUtil.close(connection,ps,resultSet);
}
}
}
控制台输出结果:
aa000
8a8a88
6a
Process finished with exit code 0
--结束END--
本文标题: 【JDBC】编程(2)-
本文链接: https://lsjlt.com/news/9033.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0