zoukankan      html  css  js  c++  java
  • 使用PrepareStatement

    包结构:
    这里写图片描述

    第一步:编写获取连接工具类

    package com.atguigu.jdbc;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Properties;
    
    /**
     * JDBC 操作的工具类
     */
    public class JdbcUtils {
    
        public static void close(ResultSet resultSet){
            try {
                if(resultSet != null){
                    resultSet.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        //关闭数据库资源
        public static void close(Connection connection){
            try {
                if(connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
        public static void close(Statement statement){
            try {
                if(statement != null){
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
        //根据配置文件获取数据库连接
        public static Connection getConnection() throws ClassNotFoundException, SQLException, IOException{
            Connection connection = null;
    
            //0. 读取 Properties 文件
            Properties properties = new Properties();
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(in);
    
            //1. 准备连接数据库的四个基本信息: 
            String driverClassName = properties.getProperty("jdbc.driverClass");
            String url = properties.getProperty("jdbc.jdbcUrl");
            String user = properties.getProperty("jdbc.user");
            String password = properties.getProperty("jdbc.password");
    
            //2. 加载驱动
            Class.forName(driverClassName);
    
            //3. 调用 DriverManager.getConnection(url, user, password) 获取连接
            connection = DriverManager.getConnection(url, user, password);
    
            return connection;
        }
    
    }

    第二步:执行插入操作

    public class JdbcTest1 {
    //向数据表插入一条记录
        @Test
        public void testInsert() throws ClassNotFoundException, SQLException, IOException{
            //1. 编写一条 SQL 语句:
            String sql = "INSERT INTO users2 (username, password) VALUES('tom','2345')";
    
            //2. 获取连接
            Connection connection = JdbcUtils.getConnection();
    
            //3. 执行 SQL 需要借助于 Statement 接口
            //3.1 调用 Connection#createStatement() 创建 Statement 对象
            Statement statement = connection.createStatement();
    
            //3.2 执行 SQL
            statement.execute(sql);
    
            //4. 关闭数据库资源
            statement.close();
            connection.close();
        }
    }
    =========================================
    /**
         * 无论是否出现异常, 都必须保证关闭数据库资源!
         * 使用 try catch finallay. 在 finally 中关闭数据库资源 
         */
        @Test
        public void testInsert2(){
            Connection connection = null;
            Statement statement = null;
    
            try {
                //1. 编写一条 SQL 语句:
                String sql = "INSERT INTO users2 (username, password) VALUES('tom','2345')";
    
                //2. 获取连接
                connection = JdbcUtils.getConnection();
    
                //3. 执行 SQL 需要借助于 Statement 接口
                //3.1 调用 Connection#createStatement() 创建 Statement 对象
                statement = connection.createStatement();
    
                //3.2 执行 SQL
                statement.execute(sql);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally{
                //4. 关闭数据库资源
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    ===========================================
    
    /*
         * 若仅仅是执行一条已经准备好的 SQL, 使用 Statement OK!
         * 开发时, 不太可能使用完全实现准备好的 SQL! SQL 中的部分开能需要动态传入. 
         */
        //调用 JdbcUtils 来关闭数据库资源
        @Test
        public void testStatement(){
            Connection connection = null;
            Statement statement = null;
    
            try {
                //1. 编写一条 SQL 语句:
                String sql = "INSERT INTO users2 (username, password) VALUES('tom','2345')";
    
                //2. 获取连接
                connection = JdbcUtils.getConnection();
    
                //3. 执行 SQL 需要借助于 Statement 接口
                //3.1 调用 Connection#createStatement() 创建 Statement 对象
                statement = connection.createStatement();
    
                //3.2 执行 SQL
                statement.execute(sql);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally{
                //4. 关闭数据库资源
                JdbcUtils.close(statement);
                JdbcUtils.close(connection); 
            }
        }
    ==========================================================
    //关于 Statement 做了解即可. 
        //用户名和密码从控制台进行动态输入
        //拼接 SQL 字符串不靠谱!
        //1. 麻烦. 2. 还会有 SQL 注入的问题. 
        @Test
        public void testStatement2(){
            Connection connection = null;
            Statement statement = null;
    
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("username:");
            String username = scanner.nextLine();
    
            System.out.println("password:");
            String password = scanner.nextLine();
    
            try {
    
                //1. 编写一条 SQL 语句:
                String sql = "INSERT INTO users (username, password) VALUES('" 
                        + username + "','" + password + "')";
    
                //2. 获取连接
                connection = JdbcUtils.getConnection();
    
                //3. 执行 SQL 需要借助于 Statement 接口
                //3.1 调用 Connection#createStatement() 创建 Statement 对象
                statement = connection.createStatement();
    
                //3.2 执行 SQL
                statement.execute(sql);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally{
                //4. 关闭数据库资源
                JdbcUtils.close(statement);
                JdbcUtils.close(connection); 
            }
        }   
    =========================================================
    /**
         * PreparedStatement 可以解决 Statement 的问题
         * 1. 不再需要拼接 SQL 字符串
         * 2. 可以解决 SQL 注入的问题.
         */
        @Test
        public void testPreparedStatement(){
            Connection connection = null;
            PreparedStatement preparedStatement = null;
    
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("username:");
            String username = scanner.nextLine();
    
            System.out.println("password:");
            String password = scanner.nextLine();
    
            try {
    
                //1. 编写一条 SQL 语句, 使用 ? 作为占位符. 所以就可以不拼 SQL 串了. 
                String sql = "INSERT INTO users (username, password) VALUES(?,?)";
    
                //2. 获取连接
                connection = JdbcUtils.getConnection();
    
                //3. 调用 Connection#prepareStatement(sql) 创建 PreparedStatement 对象
                preparedStatement = connection.prepareStatement(sql);
    
                //4. 调用 PreparedStatement 的 setXxx 方法来填充占位符
                preparedStatement.setString(1, username);
                preparedStatement.setString(2, password);
    
                //3.2 执行 SQL. 调用 execute() 方法. 而不能再调用 Statement 的 execute(sql) 方法
                preparedStatement.execute();
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally{
                //4. 关闭数据库资源
                JdbcUtils.close(preparedStatement);
                JdbcUtils.close(connection); 
            }
        }
    ==========================================================
    jdbc.properties路径:/jdbc-1/src/jdbc.properties
    内容:
    #连接MySQL
    jdbc.user=root
    jdbc.password=root
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/jdbc1
    
    #连接Oracle
    #jdbc.user=scott
    #jdbc.password=tiger
    #jdbc.driverClass=oracle.jdbc.driver.OracleDriver
    #jdbc.jdbcUrl=jdbc:oracle:thin:@127.0.0.1:1521:ORCL001
  • 相关阅读:
    以友盟+U-Push为例,深度解读消息推送的筛选架构解决方案应用与实践
    [Python图像处理] 三十三.图像各种特效处理及原理万字详解(毛玻璃、浮雕、素描、怀旧、流年、滤镜等)
    走进PEP8——代码规范
    2020全球C++及系统软件技术大会成功落下帷幕
    逆向工程,调试Hello World !程序(更新中)
    520了,用32做个简单的小程序
    细数那些年我用过的前端开发工具
    细数那些年我用过的前端开发工具
    前端几个常用简单的开发手册拿走不谢
    前端几个常用简单的开发手册拿走不谢
  • 原文地址:https://www.cnblogs.com/lisingshen/p/7499738.html
Copyright © 2011-2022 走看看