zoukankan      html  css  js  c++  java
  • 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(" 宠物主人登陆");

    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) {

    }

    }

    }

  • 相关阅读:
    记录优雅的pythonic代码
    记录python学习过程中的一些小心得
    关于理解python类的小题
    CSS3之属性选择器
    CSS3之初始
    HTML5+CSS3之离线web应用
    HTML5+CSS3之响应式视频以及iFrame下插入响应式视频的解决方案
    HTML5+CSS3之播放视频以及在IE8及以下的解决方案
    HTML5+CSS3响应式设计(二)
    HTML5+CSS3响应式设计(一)
  • 原文地址:https://www.cnblogs.com/future-zmy/p/6171477.html
Copyright © 2011-2022 走看看