JDBC动态查询MySQL中的表(按条件筛选)

动态查询实现按条件筛选。PreparedStatement 准备语句指定要查询的表头列,.setString()通过赋值指定行,.executeQuery()执行语句

在数据库test里先创建表school,内容如下

    

import java.sql.*;

public class Demo {
    public static void main(String[] args) {
        Connection con=null;//连接接口
        PreparedStatement pstmt=null;//准备语句接口
        ResultSet rs=null;//结果集
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");//加载驱动类
            //test数据库地址
            String url="jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf8&useSSL=false";
            con= DriverManager.getConnection(url,"root","123456");//连接数据库
            //pstmt=con.prepareStatement("select * from school where name=?");//创建准备语句对象(按name查询)
            //pstmt=con.prepareStatement("select * from school where sex=?");//创建准备语句对象(按sex查询)
            pstmt=con.prepareStatement("select * from school where name like ? and sex=?");//创建准备语句对象
            //pstmt.setString(1,"张三");//查询条件,1指的是第一个?,有几个?必须指定几个值。
            //pstmt.setString(1,"男");
            pstmt.setString(1,"小%");//查询条件,名字以“小”开头。%通配符,指示所有。
            pstmt.setString(2,"男");//并且性别为男
            rs=pstmt.executeQuery();
            System.out.println("id	name	sex	birthday");//"	"制表符
            while (rs.next()){//按行输出
                System.out.println(rs.getInt(1)+"	"+rs.getString(2)+"	"+rs.getString(3)+"	"+rs.getString(4));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally{
            if (rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(pstmt!=null){
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/xixixing/p/9715182.html