對(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ò)