JDBC入門3——預(yù)處理語句實(shí)現(xiàn)動(dòng)態(tài)查詢

對(duì)SQL進(jìn)行預(yù)處理可以使用通配符“?”來代替任何的字段值
然后通過setxxx()方法為SQL語句中的參數(shù)賦值

功能:使用預(yù)處理語句實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)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 =?");//預(yù)處理語句
            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("編號(hào):"+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:"+"http://localhost/tysql?useSSL=false","root","12345678");
        }catch(Exception e){
            e.printStackTrace();
        }
        return con;
    }

}

結(jié)果
MYSQL:

image.png

eclipse:
image.png

可以看到顯示在控制臺(tái)上的信息和數(shù)據(jù)庫(kù)中顯示一致,可以說明連接成功,查詢也成功
注意事項(xiàng)
1.運(yùn)行前,請(qǐng)?jiān)贛YSQL中確認(rèn)有對(duì)應(yīng)的數(shù)據(jù)庫(kù)和表
2.寫代碼時(shí)注意別打錯(cuò)字符和排錯(cuò)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容