曾梦垚

导航

PreparedStatement和Statment

使用Statment安全性差,存在SQL注入隐患

 

public static void main(String[] args) {

 

Connection conn=null;

 

Statement stmt=null;

 

ResultSet rs=null;

 

//根据控制台提示输入用户名和密码

 

Scanner input=new Scanner(System.in);

 

System.out.println("\t宠物主人登陆");

 

System.out.println("请输入用户名:");

 

String name=input.next();

 

System.out.println("请输入密码:");

 

String password=input.next();

 

 

 

try {

 

//加载数据库驱动

 

Class.forName("com.mysql.jdbc.Driver");

 

conn=DriverManager.getConnection("jdbc:mysql:///day01","root","root");

 

stmt=conn.createStatement();

 

String sql="SELECT * FROM master WHERE name='"+name+"' AND password='"+password+"'";

 

System.out.println(sql);

 

rs=stmt.executeQuery(sql);

 

if(rs.next()){

 

System.out.println("登陆成功!");

 

}else{

 

System.out.println("登陆失败");

 

}

 

 

 

} catch (Exception e) {

 

e.printStackTrace();

 

}finally{

 

try {

 

if(null!=rs){

 

rs.close();

 

}if(null!=stmt){

 

stmt.close();

 

}if(null!=conn){

 

conn.close();

 

}

 

} catch (Exception e2) {

 

 

 

}

 

使用PreparedStatement对象更新宠物信息

 

public static  void main(String[] args) {

 

Connection conn=null;

 

PreparedStatement pstmt=null;

 

 

 

String sql="UPDATE dog SET health=?,love=? WHERE id=?";

 

 

 

try {

 

//加载数据库驱动

 

Class.forName("com.mysql.jdbc.Driver");

 

 

 

conn=DriverManager.getConnection("jdbc:mysql:///day01","root","root");

 

 

 

//conn.createStatement();

 

 

 

pstmt=conn.prepareStatement(sql);

 

 

 

pstmt.setInt(1, 1234);

 

pstmt.setInt(2, 78);

 

pstmt.setInt(3, 2);

 

 

 

pstmt.executeUpdate();

 

 

 

 

 

} catch (Exception e) {

 

e.printStackTrace();

 

}finally{

 

try {

 

if(null!=pstmt){

 

pstmt.close();

 

}if(null!=conn){

 

conn.close();

 

}

 

} catch (Exception e2) {

 

}

 

}

 

 

 

}

 

posted on 2016-12-13 20:53  曾梦垚  阅读(205)  评论(0编辑  收藏  举报