其他分享
首页 > 其他分享> > jdbc 12: 模糊查询

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);
        }
    }
}

标签:jdbc,resultSet,preparedStatement,查询,uname,12,sql,import
来源: https://www.cnblogs.com/nefu-wangxun/p/16499813.html