JAVA连接mysql中preparestateme与statement的区别

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
		}
		

		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值