JDBC续集(第十九天)

1.用来登录的程序

package cn.tedu.test.Test2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Demo01 {
    public static void main(String[] args) throws Exception {
        method();

    }
    /**
     *
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception{
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost:3306/cgb2017";
        Connection root = DriverManager.getConnection(url, "root", "1234");
        return root;
    }
    private static void method(){
        try {
            Connection c = getConnection();
            Statement s = c.createStatement();
            ResultSet r = s.executeQuery("select *from user where name='wangzhenya' and passworld='5211314'");
            if (r.next()){
                System.out.println("恭喜你,登录成功");
            }else {
                System.out.println("失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.用高级传输器写登录界面

private static void method2() throws SQLException {
    Connection c=null;
    PreparedStatement s=null;
    ResultSet r=null;
    try {
        c = getConnection();
        //Statement s = c.createStatement();
        //当用户输入了特殊的名字时jack#,发生了sql攻击的现象
        //SQL攻击
        String a =new Scanner(System.in).nextLine();
        String b =new Scanner(System.in).nextLine();
        //String sql = "select *from user where name='"+a+"' and passworld='"+b+"'";
        String sql = "select * from user where name =? and passworld=?";
        s = c.prepareStatement(sql);//高级传输器
        //给SQL设计参数
        s.setString(1,a);
        s.setString(2,b);
        //执行拼接好的参数。不需要参数
        r = s.executeQuery();

        if (r.next()){
            System.out.println("恭喜你,登录成功");
        }else {
            System.out.println("失败");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        r.close();
        s.close();
        c.close();
    }
}

面试题:SQL攻击:出现了特殊的字符#,改变SQL语义,本质上是因为用了Statement传输器
        解决方案:利用全新的传输方式PreparedStatement,把SQL骨架和SQL的参数分开执行,遇到#只是当作普通的文本而不是注释
        优点:省去了拼接SQL语句的麻烦,防止了SQL攻击,高效;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员慕慕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值