JDBC中的SQL注入问题
使用预处理(
PreparedStatement
)解决SQL注入问题:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLInject {
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
// long start = System.currentTimeMillis();
// for (int i = 0; i < 100; i++)
read("name1");
// long end = System.currentTimeMillis();
// System.out.println("read:" + (end - start));
// start = System.currentTimeMillis();
// for (int i = 0; i < 100; i++)
read1("name1");
// end = System.currentTimeMillis();
// System.out.println("read1:" + (end - start));
read1("' or 1 or '");//被注入
}
static void read(String name) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;//预处理
ResultSet rs = null;
try {
// 2.建立连接
conn = JdbcUtils.getConnection();
// conn = JdbcUtilsSing.getInstance().getConnection();
// 3.创建语句
String sql = "select id, name, money, birthday from user where name=?";
ps = conn.prepareStatement(sql);
ps.setString(1, name);
// 4.执行语句
rs = ps.executeQuery();
// 5.处理结果
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t"
+ rs.getString("name") + "\t" + rs.getDate("birthday")
+ "\t" + rs.getFloat("money"));
}
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
static void read1(String name) throws SQLException {
Connection conn = null;
Statement st = null;//效率比PreparedStatement高
ResultSet rs = null;
try {
// 2.建立连接
conn = JdbcUtils.getConnection();
// conn = JdbcUtilsSing.getInstance().getConnection();
// 3.创建语句
String sql = "select id, name, money, birthday from user where name='"
+ name + "'";
st = conn.createStatement();
// 4.执行语句
rs = st.executeQuery(sql);
// 5.处理结果
while (rs.next()) {
System.out.println(rs.getObject("id") + "\t"
+ rs.getObject("name") + "\t"
+ rs.getObject("birthday") + "\t"
+ rs.getObject("money"));
}
} finally {
JdbcUtils.free(rs, st, conn);
}
}
}