http://blog.sina.com.cn/s/blog_6fd9615d01010e2h.html
简单概述:
PreparedStatement继承自Statement,但比Statement功能强大的多。
优点:
1、PreparedStatement是预编译的,比Statement速度快。
2、可以防止sql注入。
举例分析:
例一:
package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestPreparedStatement {
}
例二:说明PreparedStatement可以防止sql注入。
System.out.println("请输入用户名:");
name = input.nextLine();
System.out.println("请输入密码:");
pwd = input.nextLine();
String sql = "select * from myuser where userName = '" + name + "' and pwd = '" + pwd + "'";
Statement
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
} else {
}
当输入用户名为任意,密码为:123' or '1' = '1时,则都可以登录成功。
System.out.println("请输入用户名:");
name = input.nextLine();
System.out.println("请输入密码:");
pwd = input.nextLine();
String sql = "select * from myuser where userName = ? and pwd = ? ";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, name);
pst.setString(2, pwd);
ResultSet rs = pst.executeQuery();
System.out.println(sql);
if (rs.next()) {
} else {
}
当输入用户名为任意,密码为:123' or '1' = '1时,则都可以登录失败。防止了sql注入。