Java学习之JDBC

获取数据库的连接

  1. JDBC程序的编写步骤(图片来源尚硅谷)
    在这里插入图片描述
  2. 整个流程
    在这里插入图片描述

连接数据库的方式

  1. 普通的创建方式
 // 1.普通的创建方式
    @Test
    public void testConnection1() throws SQLException {
        Driver driver = new com.mysql.cj.jdbc.Driver();

        /**
         * url : 'jdbc:mysql://124.70.75.88:3306/xceshi'
         * jdbc:mysql: 协议
         * 124.70.75.88:3306: ip与端口
         * xceshi: 数据库名
         */

        String url = "jdbc:mysql://124.70.75.88:3306/xceshi";
        // 将用户名和密码封装到 Properties中
        Properties info = new Properties();
        info.setProperty("user", "xceshi");
        info.setProperty("password", "xceshi");

        Connection connection = driver.connect(url, info);

        System.out.println(connection);
    }
  1. 通过反射的方式进行创建
    //2. 通过反射的方式进行创建
    @Test
    public void testConntion2() throws Exception {

        // 1. 获取Driver 实现类的对象, 使用反射
        Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();

        // 2. 提供连接的数据库
        String url = "jdbc:mysql://124.70.75.88:3306/xceshi";
        // 3. 将用户名和密码封装到 Properties中
        Properties info = new Properties();
        info.setProperty("user", "xceshi");
        info.setProperty("password", "xceshi");

        // 4. 获取连接
        Connection connection = driver.connect(url, info);

        System.out.println(connection);
    }
  1. 使用 DriverManager替换Driver
	//3. 使用DriverManager替换Driver
    @Test
    public void testConntion3() throws Exception {
        // 1. 获取Driver 实现类的对象, 使用反射
        Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();

        // 2. 提供连接的基本信息
        String url = "jdbc:mysql://124.70.75.88:3306/xceshi";
        String user = "xceshi";
        String password = "xceshi";

        //3. 注册驱动
        DriverManager.registerDriver(driver);

        // 4. 获取连接
        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println(connection);

    }
  1. 对方式三进行优化,只加载驱动,不显示注册驱动
 //4. 对方式三进行优化,只加载驱动,不用显示的注册驱动就可以,因为已经有默认注册驱动的静态代码块了
    @Test
    public void testConntion4() throws Exception {
        // 1. 获取Driver 实现类的对象, 使用反射
        Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
//        Driver driver = (Driver) clazz.newInstance();

        // 2. 提供连接的基本信息
        String url = "jdbc:mysql://124.70.75.88:3306/xceshi";
        String user = "xceshi";
        String password = "xceshi";

        //3. 注册驱动
//        DriverManager.registerDriver(driver);

        // 4. 获取连接
        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println(connection);
    }
  1. 通读取配置文件(jdbc.properties)的方式
//5. 通过配置文件的方式获取连接
    @Test
    public void testConntion5() throws Exception {
        // 1. 读取配置文件的四个基本信息
        InputStream inputStream = jdbc01.class.getClassLoader().getResourceAsStream("jdbc.properties");

        Properties pros = new Properties();
        pros.load(inputStream);

        // 2. 获取配置文件的四个基本信息
        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String jdbc = pros.getProperty("jdbc");

        // 3. 加载驱动
        Class.forName(jdbc);

        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }

操作和访问数据库

数据库连接被用于向数据库服务器发送命令和SQL语句,并接受数据库服务器返回的结果,其实一个数据库连接就是一个Socket连接。
java.sql包中有三个接口分别定义了对数据库的调用的不用方式。
Statement: 对于执行静态的sql语句并返回它所生成结果的对象。
PrepatedStatement: sql语句被预编译并存储在此对象中,可以使用此对象高效的执行该语句。
CallableStatement:用于执行sql存储过程。

1.使用Statement操作数据库
(1)弊端

需要拼写sql语句,并且存在SQL注入问题
如何避免sql注入,只要用PreparedStatement(Statement扩展而来)取代Statement

  1. PreparedStatement操作数据库

封装的连接数据库与关闭类

public static Connection getConnection() throws Exception {
        Connection connection = null;

        // 1. 读取配置文件中的4个基本信息
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        pros.load(is);


        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String jdbc = pros.getProperty("jdbc");

        // 2.加载驱动
        Class.forName(jdbc);

        // 3.获取连接
        connection = DriverManager.getConnection(url, user, password);
        return connection;
    }

    public static void CloseConn(PreparedStatement preparedStatement, Connection connection) {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }

        System.out.println("关闭成功");
    }

做一个实例来增加一条数据

?: 占位符
String sql = “insert into ceshi(name,age,score)values(?,?,?)”; // 通过? 占位
preparedStatement = connection.prepareStatement(sql);
添加占位符的数据: preparedStatement.setString(1,“xxx”);

 @Test
    public void testInsert() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            // 1. 读取配置文件中的4个基本信息
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
            Properties pros = new Properties();
            pros.load(is);


            String user = pros.getProperty("user");
            String password = pros.getProperty("password");
            String url = pros.getProperty("url");
            String jdbc = pros.getProperty("jdbc");

            // 2.加载驱动
           Class.forName(jdbc);

           // 3.获取连接
            connection = DriverManager.getConnection(url, user, password);

            System.out.println(connection);

            // 4. 预编译sql语句, 返回PreparedStatement的实例
            String sql = "insert into ceshi(name,age,score)values(?,?,?)";
            preparedStatement = connection.prepareStatement(sql);

            // 5.填充占位符
            preparedStatement.setString(1,"xxx");
            preparedStatement.setInt(2,20);
            preparedStatement.setString(3,"计算机学院");

            // 6.执行操作
            preparedStatement.execute();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }

做一个实例来修改数据

@Test
    public void TestUpdate() throws Exception {
        // 初始化
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            //1. 获取数据库的连接
            connection = jdbc_conn.getConnection();

            //2. 预编译sql语句
            String sql = "update ceshi set name = ? where id = ?";
            preparedStatement = connection.prepareStatement(sql);
            //3. 填充占位符
            preparedStatement.setString(1, "贾xx");
            preparedStatement.setInt(2,2);
            //4. 执行sql
            preparedStatement.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //5. 资源的关闭
        jdbc_conn.CloseConn(preparedStatement, connection);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值