首页 > 其他分享 >02 Statement和PreparedStatement

02 Statement和PreparedStatement

时间:2024-03-22 23:33:03浏览次数:17  
标签:02 PreparedStatement statement System user Statement sql null out

文章目录

Statement

(1)相同的SQL语句, 重复执行第n次,编译n次 — 效率低
(2)Statement sql中的参数赋值 直接通过字符串拼接,可能会有非法sql注入,导致数据泄露

import java.sql.*;
import java.util.Scanner;

public class Login {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入用户名:   ");
        String userName = sc.nextLine();
        System.out.println();
        System.out.print("请输入密码:   ");
        String userPwd = sc.nextLine();



        //连接
        Connection connection = null;
        //操作对象
        Statement statement = null;
        //结果
        ResultSet resultSet = null;

        try {

            //1注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            connection = DriverManager.getConnection("jdbc:mysql:///dict?useSSL = false","root","123456");
            //3创建对象
            statement = connection.createStatement();

            //4传入结果

            String sql = " select * from user where username ='"+userName+"' and password = '"+userPwd+"';";
            resultSet = statement.executeQuery(sql);
            if (resultSet.next()){
                System.out.println("登录成功");
            }else {
                System.out.println("登录失败");
            }




        } catch (ClassNotFoundException e)
        {
            e.printStackTrace();
            System.out.println("驱动未能找到");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("sql出现问题");
        }
        finally {


            //6.关闭所有资源
            if (resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }}
            if (null!=statement){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}

PreparedStatement

(1)相同的SQL语句, 重复执行第n次,不需要重复编译 — 效率高
(2) PreparedStatement 可以有效防止sql注入 , 通过?占位符给sql中的参数赋值,
数据类型严格匹配,sql语句组成不是字符串直接拼接


import java.sql.*;
import java.util.Scanner;


public class Login2 {


    /*
     * 登录
     * 1.username&password
     * 2.找个对象给他存起来
     * 3.将这个值放到sql中然后给statement执行
     *  select * from user_name = 'name' and user_pwd = 'pwd' or 1=1
     * 4.校验结果(ResultSet):去执行next()  true则成功 不然反之
     *
     *
     *
     *  "select user_name from user where user_name ='   ' and user_pwd = 'pwd' or '1'='1';";
     *
     * */

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.print("请输入用户名:   ");
        String userName = sc.nextLine();
        System.out.println();
        System.out.print("请输入密码:   ");
        String userPwd = sc.nextLine();



        //连接
        Connection connection = null;
        //操作对象
        PreparedStatement statement = null;
        //结果
        ResultSet resultSet = null;

        //1.注册驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            connection = DriverManager.getConnection("jdbc:mysql:///test?useSSL = false","root","root");
            //3.获取操作对象
            //3.1获取预编译对象
            //提前将sql写好并为关键值用?去占位
            statement = connection.prepareStatement("select * from user where username =? and password =?");
            //3.2根据位置放入关键值
            //位置还是从1开始
            statement.setObject(1,userName);
            statement.setObject(2,userPwd);

            //4.sql编写并执行
            //预编译对象直接执行,不需要传入sql,因为已经设置好了!!!
//            String sql = "select user_name from user where user_name ='"+userName+"' and user_pwd = '"+userPwd+"';";
            resultSet = statement.executeQuery();
            //5.解析结果
            /*
             * 判断resultset的next()
             * true 成功
             * false 失败
             * */
            if (resultSet.next()){
                System.out.println("登录成功");
            }else {
                System.out.println("登录失败");
            }

        } catch (ClassNotFoundException e)
        {
            e.printStackTrace();
            System.out.println("驱动未能找到");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("sql出现问题");
        }
        finally {


            //6.关闭所有资源
            if (resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }}
            if (null!=statement){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
}

标签:02,PreparedStatement,statement,System,user,Statement,sql,null,out
From: https://blog.csdn.net/m0_46695127/article/details/136854440

相关文章

  • 今日总结2024/3/22
    今日复习了BFS的抽象用法,可以根据实际问题不断枚举所有可能Acwing1355.母亲的牛奶农夫约翰有三个容量分别为 A,B,C升的挤奶桶。最开始桶 A 和桶 B都是空的,而桶 C里装满了牛奶。有时,约翰会将牛奶从一个桶倒到另一个桶中,直到被倒入牛奶的桶满了或者倒出牛奶的桶空了为......
  • BUPT 2024 Spring Training #3(ICPC2023 杭州站)Ag复盘
    D-OperatorPrecedence求一个长度为\(2n\)的序列\(a_{2n}\)满足条件\((a_1×a_2)+(a_3×a_4)+\ldots+(a_{2n-1}×a_{2n})=a_1×(a_2+a_3)×\ldots×(a_{2n-2}+a_{2n-1})×a_{2n}\)solution构造题显然找特殊规律。考虑到乘法构造难度大于加法,可以从乘法开始考虑。......
  • 中考英语首字母快速突破014-2021上海徐汇英语二模-The Glamorous Life of TV Journali
    中考英语首字母快速突破014-2021上海徐汇英语二模-TheGlamorousLifeofTVJournalists-电视记者的风光生活PDF格式公众号回复关键字:ZKSZM014原文​HundredsofthousandsofpeopleoftenseetheirfacesontheTVscreen.Theymaybespeaking“live”from......
  • 2024-03-22
    \({\color{orange}\star}\)2024-03-22\({\color{orange}\star}\)模积和#题目描述#求\[\sum_{i=1}^{n}\sum_{j=1}^{m}(n\bmodi)\times(m\bmodj),i\neqj\]\(\bmod19940417\)的值#Solution#不妨设\(n\lem\)容斥原理\[\sum_{i=1}^{n}\sum_......
  • 不容错过的BUCK DCDC同步降压电路TPS563202
    1.TPS563202,优秀的17V转5V转3.3V降压DCDC电路参数优异,体积小,价格甚至比国产的还低,参数超过这个DCDC,价格低于这个DCDC的,请告知,国内器件厂家太多了,个人只了解一部分。12V转5V转3.3V转2.5V转1.8V都可以的。特点:标注3A,可输出3A电流,同步降压,无需外部肖特基输入电压范围:4.3V......
  • 20212217刘恒谦-Exp2 后门原理与实践
    实践过程记录使用netcat获取主机操作Shell,cron启动​ ncat即Netcat,可以收发传输层数据,由攻击者使用。cron是Linux中用于按计划执行脚本的工具,在网络对抗中让受害者连接不稳定时,重连攻击者,由受害者启动。​ 既然如此,受害者需要是Linux,否则没有cron命令,我购买了一台阿里云Ubuntu......
  • 机试重点题-2021/2023
    20215:由二叉树前々序列和中々序列得到后々序列列 #include<iostream>#include<unordered_map>usingnamespacestd;constintN=50010;intn;inta[N],b[N];//前序,中序unordered_map<int,int>p;voidbuild(intal,intar,intbl,intbr){if(al......
  • CCF软件能力认证202312-1——仓库规划
    问题描述西西艾弗岛上共有个仓库,依次编号为。每个仓库均有一个维向量的位置编码,用来表示仓库间的物流运转关系。具体来说,每个仓库均可能有一个上级仓库,满足:仓库位置编码的每一维均大于仓库位置编码的对应元素。比如编码为的仓库可以成为的上级,但不能成为的上级。如......
  • [周报]线性代数和SAM 2024年3月第3周
    算法笔记线性代数线代题不多,但是都很有些难度.当然OI中的线性代数存在很大程度上的"只取所需"的情况.高斯消元,线性(异或)基加上矩阵优化DP,基本上就是最多的一个运用了.高斯消元道理就是初中数学,解多元一次方程组.其实这种用方程组来理解线代是个挺直观的方法.比如向量张成......
  • 2024中考记录
    写篇博客记录下中考倒计时一百天发生的事,有空就更新。开始时间:\(2024.3.22\),距离中考一百天。\(Day\)-100从昨天开始月考,校内一模,和综合排名有关。第一天,英语难!!!,平时写的作业太水了,智商直接退化。化学考前听说很难,实际体验还好,时间分配垃圾,差点没写完。本来是二十分结束,记错......