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

    }

    }

    }

  • 相关阅读:
    ElasticSearch2.3.1环境搭建哪些不为人知的坑
    don't run elasticsearch as root.
    翻译 Asp.Net Core 2.2.0-preview1已经发布
    微信小程序与AspNetCore SignalR聊天实例
    .Net Core扩展 SharpPlugs简单上手
    Docker折腾手记-linux下安装
    C#3.0 扩展方法
    微软微服务eShopOnContainers示例之EventBusRabbitMq解析与实践
    C#3.0智能的编译器
    C#3.0导航
  • 原文地址:https://www.cnblogs.com/future-zmy/p/6171477.html
Copyright © 2011-2022 走看看