JDBC入门3——预处理语句实现动态查询

2018-05-17  本文已影响0人  从0到1的小姐姐

对SQL进行预处理可以使用通配符“?”来代替任何的字段值
然后通过setxxx()方法为SQL语句中的参数赋值

功能:使用预处理语句实现对数据库tysql中stu表的id=2的查询和输出
代码

import java.sql.*;
public class Prep {
    static Connection con;
    static PreparedStatement sql;
    static ResultSet res;
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Prep c = new Prep();
        con = c.getConnection();
        try{
            sql = con.prepareStatement("select * from stu where id =?");//预处理语句
            sql.setInt(1,2);
            res = sql.executeQuery();
            while(res.next()){
                String id = res.getString(1);
                String name = res.getString("name");
                String sex = res.getString("sex");
                String birthday = res.getString("birthday");
                System.out.println("编号:"+id);
                System.out.println("姓名:"+name);
                System.out.println("性别:"+sex);
                System.out.println("生日:"+birthday);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public Connection getConnection(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql:"+"//localhost/tysql?useSSL=false","root","12345678");
        }catch(Exception e){
            e.printStackTrace();
        }
        return con;
    }

}

结果
MYSQL:

image.png
eclipse:
image.png
可以看到显示在控制台上的信息和数据库中显示一致,可以说明连接成功,查询也成功
注意事项
1.运行前,请在MYSQL中确认有对应的数据库和表
2.写代码时注意别打错字符和排错
上一篇下一篇

猜你喜欢

热点阅读