preparestatement与statement在使用时的区别
1,Statement:
定义statemen 语句-》
编写sql语句-》
执行executeUpdate(sql)。
举例:尽量使用preparestatement,使用preparestatement可有效防止sql注入
-----------------------------------------------------------
2 ,preparestatement:
–》编写sql语句(可能存在占位符?)
–》在创建preparestatement对象是,将sql预编译:preparestatement(sql)
–》执行executeUpdate()<这里括号里不要填写sql,应为已经预编译过了>
–》用setXXX()语句替换占位符。
举例:
public class JDBCDemo4 {
public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver";
public static final String DBURl = "jdbc:mysql://localhost:3306/Student?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
public static final String DBUSER = "root";
public static final String DBPASS = "qwert123";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement prstmt = null;
try {
//导入驱动程序
Class.forName(DBDRIVER);
//与数据库建立连接
conn=DriverManager.getConnection(DBURl,DBUSER,DBPASS);
//发送sql执行(增删改查)
String sql="insert into student values(1013,'zhangsan','women','class8',95,null)";
String sql1 = "INSERT INTO STUDENT VALUES(1015,'zhangsan12321','women','class5',95,20)";
String delsql="delete from student where id =1011";
prstmt = conn.prepareStatement(sql);
int count=prstmt.executeUpdate();
if(count>0){
System.out.println("成功");
}else {
System.out.println("失败");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("数据加载失败");
}
try {
if(prstmt!=null)
prstmt.close();
if (conn!=null)
conn.close();
} catch (Exception e) {
// TODO: handle exception
}
}