5.PreparedStatement(尚硅谷笔记)

PreparedStatement是Statement的子接口,可以传入带占位符的sql语句,并且提供了补充占位符变量的方法,可以有效地禁止sql注入,最大可能提高性能。

使用PreparedStatement

1.创建PreparedStatement

PreparedStatement ps=connection.prepareStatement(sql);

2.调用PreparedStatement的setXxx(int index,object val)设置占位符的值,index从1开始。

3.执行sql语句:executeQuery()或executeUpdate(),执行时不需要再传入sql语句。

public static void update(String sql,Object...args) {
	Connection connection=null;
	Statement statement=null;
	PreparedStatement preparedStatement=null;
	try {
		connection=getConnection();
		preparedStatement=connection.prepareStatement(sql);
		for(int i=0;i<args.length;i++) {
			preparedStatement.setObject(i, args[i]);
		}
		preparedStatement.executeUpdate(sql);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		release(null,preparedStatement,connection);
	}
}
发布了90 篇原创文章 · 获赞 48 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Asher_S/article/details/90246293
今日推荐