jdbc 12: 模糊查询

jdbc连接mysql,进行模糊查询

package com.examples.jdbc.o11_模糊查询;

import com.examples.jdbc.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 借助自定义的jdbc工具类,完成jdbc模糊查询
 */
public class Test {
    public static void main(String[] args) {
        likelySearch();
    }

    /**
     * 自定义jdbc工具类,实现模糊查询
     */
    private static void likelySearch() {
        //3个资源对象
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            //1.自定义工具类,获取jdbc数据库连接对象
            connection = DBUtils.getConnection();

            //2.
            String sql = "select * from tb_user where uname like ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "__");
            resultSet = preparedStatement.executeQuery();

            //3.
            while(resultSet.next()){
                int id = resultSet.getInt("id");
                String uname = resultSet.getString("uname");
                String upasswd = resultSet.getString("upasswd");
                System.out.println("id: " + id + " uname: " + uname + " upasswd: " + upasswd);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //4.自定义工具类,关闭jdbc资源对象
            DBUtils.close(connection, preparedStatement, resultSet);
        }
    }
}
posted @   nefu-xun  阅读(190)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示