当前位置: 首页 > 图灵资讯 > 技术篇> JDBC

JDBC

来源:图灵教育
时间:2023-10-06 09:49:22

JDBC是一套API,采用Java语言操作关系数据库,全称:(Java DataBase Connectivity)Java数据库连接。

JDBC的本质:

image.png

基本使用如下所示(首先,我们需要导入jar包):

import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;public class Test1 {    public static void main(String[] args) throws ClassNotFoundException, SQLException {        ///注册驱动(MySQL5后不能写)        Class.forName("com.mysql.cj.jdbc.Driver");        //获取连接        String url = "jdbc:mysql://127.0.0.1:3306/my_test";        String userName = "root";        String userPassword = "1234";        final Connection connection = DriverManager.getConnection(url, userName, userPassword);        //定义SQL语句        String sql = "update test set sex = '女' where id = 1 ";        ///获取执行sql的对象        Statement stmt = connection.createStatement();        //执行sql语句        int count = stmt.executeUpdate(sql);    ////这种方法返回受影响的行数        //处理结果        System.out.println("受影响的行数为:" + count);        ///释放资源        stmt.close();        connection.close();    }}
1、JDBC的API

1.1、DriverManager(它是一个工具类,它提供了许多控制数据库的方法)

功能:注册驱动,获取数据库连接

1.2、Connection(数据库连接对象)

功能:获取执行sql的对象,管理事务

image.png

image.png

使用如下所示:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;public class Test2 {    public static void main(String[] args) throws SQLException {        String url = "jdbc:mysql://127.0.0.1:3306/my_test";        String userName = "root";        String userPassword = "1234";        //获取连接        final Connection connection = DriverManager.getConnection(url, userName, userPassword);        //定义SQL语句        String sql1 = "update test set age = 20211 where id = 1 ";        String sql2 = "update test set age = 20231 where id = 2 ";        //获取执行sql的对象        Statement stmt = connection.createStatement();        try {            //开始事务            connection.setAutoCommit(false);            //执行sql语句            int count1 = stmt.executeUpdate(sql1);    ////这种方法返回受影响的行数            //处理结果            System.out.println("受影响的行数为:" + count1);            //异常情况            int a = 2 / 0;            //这两个sql都不会被执行            int count2 = stmt.executeUpdate(sql2);            System.out.println("受影响的行数为:" + count2);            ///提交事务            connection.commit();        } catch (Exception e) {            //回滚事务            connection.rollback();            //输出错误信息            e.printStackTrace();        }        ///释放资源        stmt.close();        connection.close();    }}

1.3、Statement

执行sql语句。

image.png

1.3.2、excuteQuery(sql):

image.png

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class Test3 {    public static void main(String[] args) throws Exception {        String url = "jdbc:mysql://127.0.0.1:3306/my_test";        String userName = "root";        String userPassword = "1234";        //获取连接        final Connection connection = DriverManager.getConnection(url, userName, userPassword);        //定义SQL语句        String sql = "select * from test";        ///获取执行sql的对象        Statement stmt = connection.createStatement();        //执行sql语句        final ResultSet rs = stmt.executeQuery(sql);/*                //处理结果,遍历数据        while (rs.next()){            //参数表示第几行,注意下标从1开始            int id = rs.getInt(1);            String name = rs.getString(2);            String sex = rs.getString(3);            int age = rs.getInt(4);            System.out.println("id = " + id + "\t姓名:" + name + "\t性别:" + sex + "\t年龄:" + age);        }        System.out.println("--------------------------------");*/        //也可以写列名        while (rs.next()) {            //参数表示第几行,注意下标从1开始            int id = rs.getInt("id");            String name = rs.getString("name");            String sex = rs.getString("sex");            int age = rs.getInt("age");            System.out.println("id = " + id + "\t姓名:" + name + "\t性别:" + sex + "\t年龄:" + age);        }        ///释放资源       rs.close();        stmt.close();        connection.close();    }}

综合案例(将每个数据封装成Java对象):image.png

import java.sql.*;import java.util.ArrayList;public class Test4 {    public static void main(String[] args) throws SQLException {        String url = "jdbc:mysql://127.0.0.1:3306/my_test";        String userName = "root";        String userPassword = "1234";        //获取连接        final Connection connection = DriverManager.getConnection(url, userName, userPassword);        //定义SQL语句        String sql = "select * from test";        ///获取执行sql的对象        Statement stmt = connection.createStatement();        //执行sql语句        final ResultSet rs = stmt.executeQuery(sql);        ///创建ArrayList集合        ArrayList<Person> list = new ArrayList<>();        从数据库中查询到的数据//遍历,然后将数据放入对象中,将对象放入ArrayList集中        while (rs.next()){            int id = rs.getInt("id");            String name = rs.getString("name");            String sex = rs.getString("sex");            int age = rs.getInt("age");            ////创建Java对象            Person p = new Person();            p.setId(id);            p.setName(name);            p.setSex(sex);            p.setAge(age);            ///将对象添加到ArrayList集合中            list.add(p);        }        ///遍历集合        for (Person person : list) {            System.out.println(person);        }        ///关闭资源        rs.close();        stmt.close();        connection.close();    }}

1.4、PreparedStatement(sql语句的预编译和执行可以防止sql注入问题)

==sql注入:sql注入是通过操作输入修改事先定义的sql语句,以实现执行代码攻击服务器的方法。==

image.png

具体使用如下:

import java.sql.*;import java.util.Scanner;public class Test5 {    public static void main(String[] args) {        ///创建输入对象        Scanner sc = new Scanner(System.in);        System.out.print("请输入姓名:");        String name = sc.next();        System.out.print("请输入密码:");        int password = sc.nextInt();        ////调用用户登录的方法        try {            loginInject(name, password);        } catch (SQLException e) {            e.printStackTrace();        } finally {            sc.close();        }    }    ///用户登录    public static void userLogin(String lName, int lPassword) throws SQLException {        String url = "jdbc:mysql://127.0.0.1:3306/my_test";        String userName = "root";        String userPassword = "1234";        //获取连接        final Connection connection = DriverManager.getConnection(url, userName, userPassword);        //定义SQL语句(这样拼接可能会导致SQL注入问题,因为有些SQL在拼接时会改变以下SQL的含义,从而改变以下sql的最终意义)        String sql = "select* from user where name = '" + lName + "' and password = '" + lPassword + "'";        ///获取执行sql的对象        Statement stmt = connection.createStatement();        //执行sql语句        final ResultSet rs = stmt.executeQuery(sql);        ///判断登录是否成功        if (rs.next()) {            System.out.println("登录成功!");        } else {            System.out.println("登录失败!");        }        ///释放资源        rs.close();        stmt.close();        connection.close();    }    //解决sql注入问题    public static void loginInject(String lName, int lPassword) throws SQLException {        String url = "jdbc:mysql://127.0.0.1:3306/my_test";        String userName = "root";        String userPassword = "1234";        //获取连接        final Connection connection = DriverManager.getConnection(url, userName, userPassword);        //定义SQL语句        String sql = "select* from user where name = ?  and password = ? ";        //获得pstmt对象        final PreparedStatement pstmt = connection.prepareStatement(sql);        ////向上述参数传递值        pstmt.setString(1, lName);        pstmt.setInt(2, lPassword);        //执行sql        final ResultSet rs = pstmt.executeQuery();        ///判断登录是否成功        if (rs.next()) {            System.out.println("登录成功!");        } else {            System.out.println("登录失败!");        }        ///释放资源        rs.close();        pstmt.close();        connection.close();    }    }

==注:以上方法不仅适用于查询,还适用于添加、修改和删除!!!==

2、数据库连接池

数据库连接池是负责数据库连接分配和管理的容器(Connection)它允许应用程序重复使用现有的数据库连接,而不是重建一个。释放空闲时间超过最大空闲时间的数据库连接,以避免因未释放数据库连接而导致的数据库连接遗漏。优点:

①、资源重用②、提高系统响应速度③、避免数据库连接遗漏

2.1、连接到Driud数据库的连接池

使用步骤:

image.png

==点击此处下载jar包==

配置文件的定义如下:image.png

基本使用如下:

import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;import java.io.FileInputStream;import java.sql.Connection;import java.util.Properties;public class Test6 {    public static void main(String[] args) throws Exception {        //加载配置文件        Properties prop = new Properties();        prop.load(new FileInputStream("./Date10_2//src/Test2//druid.properties"));        //获取连接池对象        final DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);        //获取数据库连接        final Connection connection = dataSource.getConnection();    }}