SQL语句(statement)预处理(preparedStatement)

javaweb中sql语句的预处理


预处理也叫预编译。本来sql每执行一条sql语句,就需要对这条sql语句进行编译,然后执行。预编译采用sql模版。只需要在第一次使用时编译一次。后面传参数调用就可以了。

说明一下 PreparedStatement 是Statement的子接口

预处理代码如下:

try{
			Connection con = DriverManager.getConnection(props.getProperty("url"),props.getProperty("username"),props.getProperty("password"));
			String sql = "insert into batch values(?,?,?)";
		
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, 1);
			pstmt.setString(2, "fly");
			pstmt.setString(3, "女");
			pstmt.executeUpdate();
		}catch(Exception e ){
			throw new RuntimeException(e);
		}

这里获取Connection对象的方法是通过将数据库参数写在一个dbconfig.properties配置文件中,在程序中加载配置文件来获取的。如何将mysql参数写在配置文件并在程序中获取到?步骤如下:
1.首先new file 取名为***.properties
2.在properties视图里面点击右上角的add一次添加四大参数。

3.程序中读取配置信息。
3.1 实例化一个properties。  Properties props = new Properties();
3.2通过类加载器,将类路径下的配置文件夹在进来。
InputStream in = 类名.class.getClassLoader().getResourceAsStream("*.properties");
3.3通过properties的load方法加载配置信息。
props.load(in);

这样,配置文件里面的内容就到了Properties对象中了。获取方式:
String  driverClassName =  props.getProperty("driverClassName");


预处理的优点:

1.可以方式SQL攻击。
2.提高代码的可读性和可维护性。
3.提高代码效率。

实现sql语句预处理的流程如下:

1.获得Connection数据库连接对象。
2.创建一个sql模版。例如:String sql = insert into user  values(?,?,?);
3.得到预处理对象. PreparedStatement pstmt = con.prepareStatement(sql);
4.给sql模版中的问号赋值(这里的赋值需要注意,不能多赋不能少赋)。  例如: stmt.setString(1,"张三");  第一个参数1表示给第一个问号赋值。
5.执行sql模版 pstmt.executeUpdate(). / pstmt.executeQuery().
如果有结果集,就正常对结果集进行解析。
这样就实现了sql的语句预处理。
需要注意的是,从mysql4.0之后,mysql的预处理默认是关闭的,需要在url参数后面添加参数进行开启,参数如下:?useServerPrepStmts=true&cachePrepStmts=true

你可能感兴趣的:(javaweb)