import java.sql.*;
/*
* 解决sql注入问题:
* PreparedStatement接口继承了java.sql.Statement,是属于预编译数据库操作对象
* 原理:预先对sql语句的框架进行编译,再给sql语句传值,用户提供的信息中即使含
* 有sql语句关键字,但是这些关键字并没有参与编译不起作用。
*
* 用户名:abc
* 密码: abc' or '1'='1
*/
public class PreparedStatementTest
{
public static void main(String[] args)throws Exception{
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取数据库连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//3、获取数据库连接对象
String sql = "select * from emp where ename = ?"; //?表示占位符
PreparedStatement ps = conn.prepareStatement(sql); //这里使用PreparedStatement预编译数据库操作对象
//给占位符传值,1表示给第一个问号传值,2则表示给第二个问号传值
ps.setString(1,"king");
//4、执行sql语句
ResultSet rs = ps.executeQuery();
//5、处理查询结果集
while(rs.next()){
String ename = rs.getString("ename");
int empno = rs.getInt("empno");
String job = rs.getString("job");
int mgr = rs.getInt("mgr");
Date date = rs.getDate("hiredate");
double sal = rs.getDouble("sal");
double comm = rs.getDouble("comm");
int deptno = rs.getInt("deptno");
System.out.println("ename="+ename+" emptno="+empno+" job="+job+" mgr="+mgr+" date="+date+sal+" comm="+comm+" deptno="+deptno);
}
//6、关闭释放
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
}
}
08-21