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\tname\tsex\tbirthday");//"\t"制表符
            while (rs.next()){//按行输出
                System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值