14MySQL连接数据库

本文详细介绍了如何使用Java通过jar包连接MySQL数据库,包括下载jar包、加载驱动、建立连接、预编译防止SQL注入,以及提供了一个优化后的示例代码.
摘要由CSDN通过智能技术生成

MySQL连接数据库

jar包的下载

要先使用java连接数据库,需要使用对应的jar包。jar包如何下载呢?

  1. 首先进入mysql官网:MySQL
  2. 进入官网后找到下载按钮,点进去

image.png

  1. 找到MySQL Community (GPL) Downloads »,点进去

  2. 找到Connector/J,再点进去

image.png

  1. 找到下面这个按钮,继续点进去

image.png

  1. 找到自己需要的jar包就可以下载了

image.png

  1. 下载之后解压,在自己的项目中创建一个lib文件夹,把jar包放进去

image.png

  1. 右键选择该jar包,点击

image.png

之后我们就可以使用这个jar包与mysql数据库建立连接了

建立连接的步骤

  1. 加载驱动:两种方式,第一种使用DriverManager.registerDriver(new Driver()),第二种使用反射的方式Class.forName(“com.mysql.jdbc.Driver”)
//方式1
DriverManager.registerDriver(new Driver());
//方式2
Class.forName("com.mysql.jdbc.Driver");
  1. 建立连接:

image.png

//建立连接
Connection connection = DriverManager.getConnection("jdbc:mysql://192.168.31.100:3306/demo?useSSL=false", "root", "123456");

  1. 创建Statement对象
//获取Statement对象
Statement statement = connection.createStatement();
  1. 编写sql语句
//编写sql语句
String sql="insert into Student (Sid,Sname,Sage,Ssex) values (20,'yz','2000-10-10 00:00:00','男')";
  1. 执行sql:当执行插入、删除等更新数据库的语句时使用executeUpdate、使用查询语句时使用executeQuery
//执行sql语句
statement.executeUpdate(sql);

当执行查询语句时,会返回一个ResultSet,该对象类似于迭代器,有next方法判断下一个数据是否为空,不为空返回true,也可以通过该对象通过get对应的数据类型(“字段名”)的方式获取查询所得的数据。

ResultSet resultSet = statement.executeQuery(selectSql);
       while (resultSet.next()){
            System.out.println(resultSet.getInt("Sid"));
            System.out.println(resultSet.getString("Sname"));
            System.out.println(resultSet.getString("Ssex"));
            System.out.println(resultSet.getDate("Sage"));
        }
  1. 关闭连接
//关闭连接
statement.close();
connection.close();

sql注入的问题

例如:

public class UserLogin {
    /*
    模拟用户的注册和登录
     */
    static Scanner scanner = new Scanner(System.in);
    static Connection connection;
    static Statement statement;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            connection = DriverManager.getConnection("jdbc:mysql://192.168.31.100:3306/demo?useSSL=false", "root", "123456");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) throws SQLException {

        System.out.println("请选择你的选项 1.登录  2.注册");
        if (scanner.hasNextInt()) {
            int choice = scanner.nextInt();
            if (choice == 1) {
                login();
            } else {
                register();
            }
        }
        connection.close();

    }

    public static void login() throws SQLException {
        System.out.println("======登录界面=======");
        String name = null;
        String pwd = null;
        System.out.println("输入姓名");
        if (scanner.hasNext()) {
            name = scanner.next();
        }
        System.out.println("输入密码");
        if (scanner.hasNext()) {
            pwd = scanner.next();
        }
        statement = connection.createStatement();
        String sql = "select count(*) as cnt from user where name='" + name + "'and pwd='" + pwd + "'";
        System.out.println(sql);
        ResultSet resultSet = statement.executeQuery(sql);
        if (resultSet.next()){
            int cnt = resultSet.getInt("cnt");
            if (cnt==1){
                System.out.println("登录成功");
            }else {
                System.out.println("登录失败");
            }
        }
        statement.close();


        /*
        编写sql
         */


    }

    public static void register() throws SQLException {
        System.out.println("=====注册界面======");
        String name = null;
        String pwd = null;
        System.out.println("输入姓名");
        if (scanner.hasNext()) {
            name = scanner.next();
        }
        System.out.println("输入密码");
        if (scanner.hasNext()) {
            pwd = scanner.next();
        }
        statement = connection.createStatement();
        String sql = "insert into user (name,pwd) values ('" + name + "','" + pwd + "')";
        System.out.println(sql);
        int i = statement.executeUpdate(sql);
        System.out.println("执行结果" + i);
        if (i > 0) {
            System.out.println("注册成功");

        } else {
            System.out.println("注册失败");
        }
        statement.close();

    }
}

上面的代码在传入密码时,加上’or’1’='1,即使密码错误也会返回结果,如何解决呢?

两种方法:1.使用hash函数。2.使用预编译

预编译的实现方式:先编写sql时对传入的字段值使用 ?占位,在使用connection创建对象时,不要创建Statement,而是创建一个PreparedStatement对象,之后把sql传入PreparedStatement对象进行预编译。之后再对?占位的地方使用preparedStatement.setString()的方式赋值,注意:这里的传值可以根据 ?的顺序传值,下标从1开始

对上述代码的优化如下:

public class UserloginPlus {
    /*
    对于上一个程序,若在传入密码时,加上'or'1'='1,则会导致sql注入
    解决方法:
        1.使用hash
        2.使用预编译
     */
    static Scanner scanner = new Scanner(System.in);
    static Connection connection;
    static Statement statement;

    static {
        //加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        //建立连接
        try {
            connection = DriverManager.getConnection("jdbc:mysql://192.168.31.100:3306/demo?useSSL=false", "root", "123456");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws SQLException {
        System.out.println("请选择你的选项 1.登录  2.注册");
        if (scanner.hasNextInt()) {
            int choice = scanner.nextInt();
            if (choice == 1){
                login();
            }else {
                register();
            }
        }
    }
public static void login() throws SQLException {
    System.out.println("======登录界面=======");
    String name = null;
    String pwd = null;
    System.out.println("输入姓名");
    if (scanner.hasNext()) {
        name = scanner.next();
    }
    System.out.println("输入密码");
    if (scanner.hasNext()) {
        pwd = scanner.next();
    }
//    statement = connection.createStatement();
    //对于需要添加的值,需要用?占位
    String sql = "select count(*) as cnt from user where name=? and pwd=?";
    //得到一个PreparedStatement对象,该对象有方法可以对sql中的?进行传值
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    //setString,方法可以传入索引和值,索引下标从1开始
    preparedStatement.setString(1,name);
    preparedStatement.setString(2,pwd);
    //preparedStatement对象也有 statement的方法executeQuery等
    ResultSet resultSet = preparedStatement.executeQuery();
    if (resultSet.next()) {
        int res = resultSet.getInt("res");
        if (res == 1) {
            System.out.println("登录成功...");
        }else {
            System.out.println("登录失败...");
        }
        // 如果有值,那么next为true
    }
    preparedStatement.close();

}
public static void register() throws SQLException {
        String name = null;
        String pwd = null;
        System.out.println("输入姓名");
        if (scanner.hasNext()) {
        name = scanner.next();
    }
        System.out.println("密码");
    if (scanner.hasNext()) {
        pwd = scanner.next();
    }
    statement = connection.createStatement();
    String sql = "insert into user (name,pwd) values ('" + name + "','" + pwd + "')";
    System.out.println(sql);
    int i = statement.executeUpdate(sql);
    System.out.println("执行结果" + i);
    if (i > 0) {
        System.out.println("注册成功");

    } else {
        System.out.println("注册失败");
    }
    statement.close();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值