zoukankan      html  css  js  c++  java
  • 工具类TestTools

    一些方法可能要使用到该工具类,该工具类中的方法包括从链接数据库到数据表中记录的增删改查。

    package JDBCTest;
    
    import java.io.InputStream;
    import java.lang.reflect.Field;
    import java.sql.Connection;
    import java.sql.Date;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Properties;
    import org.junit.Test;
    
    /**
     * 操作JDBC的工具类,封装了一些工具方法。
     *包括:   1.获取数据库连接方法 
     *      2.对数据表增删改的方法
     *      3.对数据表查找的方法
     *      4.使用反射为对象的属性赋值
     *      5.关闭Statement对象和Connection连接。
     *      6.关闭ResultSet、Statement、Connection连接。
     *      7.SQL注入。
     *      8.使用PerparedStatement查询数据判断是否登陆成功。
     *      5.关闭3个连接的方法
     *以上方法皆为静态方法。
     * 版本:1.0
     *
     */
    public class TestTools {
    
        /**
         * 1.获取数据库连接
         * 步骤:
         * 1.准备链接数据库的4个字符串
         *      1_1.创建Properties对象
         *      1_2.获取jabc.properties对应的输入流
         *      1_3.加载1_2对应的输入流 
         *      1_4.获取具体数据(Driver、url、user、password)
         * 2.加载数据库驱动程序(对应的Driver实现类中有注册驱动的代码块)
         * 3.通过DriverManager的getConnection()方法获取数据库链接
         * 
         */
        public static Connection getConnection() throws Exception{
            //1_1.创建Properties对象
            Properties properties = new Properties();
            //1_2.获取jdbc.properties输入流
            InputStream is = TestTools.class.getClassLoader().
                    getResourceAsStream("jdbc.properties");
            //1_3.加载对应发输入流
            properties.load(is);
            //1_4.获取具体信息
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String jdbcUrl = properties.getProperty("jdbcUrl");
            String driver = properties.getProperty("driver");
            //2.加载数据库驱动程序
            Class.forName(driver);
            //3.通过DriverManager的getConnection()方法获取数据库链接,并返回
            return DriverManager.getConnection(jdbcUrl, user, password);
        }
    
        /**
         * 2.操作数据库,包括增、删、改操作。
         * 获取数据库链接(Connection)之后,使用(Statement)操作数据库,对数据库进行增删改操作。
         */
        public static void getStatement(){
            Connection conn = null;
            Statement statement = null;
            try {
                //1.获取数据库连接
                conn = TestTools.getConnection();
                //2.准备插入的语句
                //增
                String sql1 = "INSERT INTO CUSTOMERS (NAME,AGE,BIRTH,address) " +
                        "VALUES ('王五','23','1995-05-12','河南省')";
                //删
                String sql2 = "DELETE FROM CUSTOMERS WHERE id = 1 ";
                //改
                String sql3 = "UPDATE CUSTOMERS SET NAME = '张辽' WHERE id = '5'";
                //3_1.获取操作SQL语句的Statement对象
                statement = conn.createStatement();
                //3_2.调用Statement对象的executeUpdate(sql)方法,执行SQL语句进行插入
                statement.execute(sql1);
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                //4.关闭连接
                TestTools.release(statement, conn);
            }
        }
    
        /**
         * 2_1.通用方法,对2.方法进行了通用性的修改,功能不变包括增、删、改操作。使用Statement进行数据表更新,包括增、删、改操作,但不包括查询。
         * 获取数据库链接(Connection)之后,使用(Statement)操作数据库,对数据库进行增删改操作。
         */
        public static void update(String sql){
            Connection conn = null;
            Statement statement = null;
            try {
                //1.获取数据库连接
                conn = TestTools.getConnection();
                //2.获取操作SQL语句的Statement对象
                statement = conn.createStatement();
                //3.调用Statement对象的executeUpdate(sql)方法,执行SQL语句进行插入
                statement.execute(sql);
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                //4.关闭连接
                TestTools.release(statement, conn);
            }
        }
        /**
         * 2_2.通用方法,对2_1.方法进行了修改,功能不变包括增、删、改操作。使用PreparedStatement进行数据表更新。
         * Object ... args:表示可变参数。
         * preparedstatement.executeUpdate();该方法用于更新。
         * preparedstatement.executeQuery();该方法用于查询。
         */
        public static void update(String sql ,Object ... args){
            //1.获取链接
            Connection conn = null;
            //2.获取Preparedtatement对象
            PreparedStatement preparedstatement = null;
            try {
                conn = TestTools.getConnection();
                preparedstatement = conn.prepareStatement(sql);
                //3.由于是可变参数,所以使用for循环,设置sql语句的占位符
                for(int i = 1; i < args.length; i++){
                    preparedstatement.setObject(i+1, args[i]);
                }
                //4.执行更新
                preparedstatement.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                //5.关闭连接
                TestTools.release(preparedstatement, conn);
            }
    
        }
    
        /**
         * 3.操作数据库,对数据库进行查询操作,
         * 步骤:
         * 1.获取Connection连接
         * 2.获取Statement对象
         * 3.Statement对象调用executeQuery(sql)方法,执行查询操作返回结果给ResultSet对象。
         * 4.处理ResultSet对象
         * 5.关闭所有连接
         */
        public static void getResultSet(){
            Connection conn = null;
            Statement state = null;
            ResultSet rs = null;
            try {
                //1.获取连接
                conn = TestTools.getConnection();
                //2.获取Statement对象
                state = conn.createStatement();
                //3.Statement对象调用executeQuery(sql)方法
                String sql = "select * from customers";
                rs = state.executeQuery(sql);
                //4.处理rs
                while(rs.next()){
                    int id = rs.getInt(1);
                    String name = rs.getString(2);
                    String age = rs.getString(3);
                    Date birth = rs.getDate(4);
                    String address = rs.getString(5);
                    System.out.println(id);
                    System.out.println(name);
                    System.out.println(age);
                    System.out.println(birth);
                    System.out.println(address);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                //5.关闭连接
                TestTools.release(rs, state, conn);
            }
        }
    
        /**
         * 3_1.通用方法,对3.方法进行修改,功能不变:对数据库进行查询操作,根据传入的参数查找是否存在该学生。,
         * 步骤:
         * 1.获取Connection连接
         * 2.获取Statement对象
         * 3.Statement对象调用executeQuery(sql)方法,执行查询操作返回结果给ResultSet对象。
         * 4.处理ResultSet对象
         * 5.关闭所有连接
         */
        public static void query(String sql){
            Connection conn = null;
            Statement state = null;
            ResultSet rs = null;
            try {
                //1.获取连接
                conn = TestTools.getConnection();
                //2.获取Statement对象
                state = conn.createStatement();
                //3.Statement对象调用executeQuery(sql)方法
                rs = state.executeQuery(sql);
                //4.处理rs
                while(rs.next()){
                    int id = rs.getInt(1);
                    String name = rs.getString(2);
                    String age = rs.getString(3);
                    Date birth = rs.getDate(4);
                    String address = rs.getString(5);
                    System.out.println(id);
                    System.out.println(name);
                    System.out.println(age);
                    System.out.println(birth);
                    System.out.println(address);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                //5.关闭连接
                TestTools.release(rs, state, conn);
            }
        }
        /**
         * 3_2.通用方法,对3.方法进行修改,用户可以传进sql一语句和某个字段,使之更加灵活。
         *功能不变:对数据库进行查询操作,根据传入的参数查找是否存在该学生。
         */
        public static Student query(String sql, Object ... args){
                Student student  = null;
                Connection conn = null;
                PreparedStatement preparedstatement = null;
                ResultSet rs = null;
                try {
                    //2.开始连接数据库
                    conn = TestTools.getConnection();
                    //3.获取Statement对象
                    preparedstatement = conn.prepareStatement(sql);
                    //4.使用executeQuery()方法,执行查询
                    rs = preparedstatement.executeQuery(sql);
                    if(rs.next()){
                        student = new Student();
                        student.setFlowID(rs.getInt(1));
                        student.setType(rs.getInt(2));
                        student.setIDCard(rs.getString(3));
                        student.setExamCard(rs.getString(4));
                        student.setStudentName(rs.getString(5));
                        student.setLocation(rs.getString(6));
                        student.setGrade(rs.getInt(7));
                    }else{
                        return null;
                    }
    
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    //5.关闭连接
                    TestTools.release(rs, preparedstatement, conn);
                }
                return student;
        }
    
        /**
         * 4.使用反射为对象的属性赋值
         * @param entity:对象
         * @param fieldName:属性名
         * @param fieldValue:属性值
         */
        public static void setFieldValue(Object entity,String fieldName,Object fieldValue){
            try {
                //首先通过反射获取指定名称的变量。
                Field Name = entity.getClass().getDeclaredField(fieldName);
                //设置私有的变量允许访问。
                Name.setAccessible(true);
                //Name调用set(对象,值)方法,为获取到的变量赋值
                Name.set(entity, fieldValue);
    
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    
    
        /**
         * 5.关闭Statement对象和Connection连接。
         */
        public static void release(Statement statement,Connection conn){
            if(statement != null){
                //1.关闭statement对象
                try {
                    statement.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if(conn != null){
                //2.关闭数据库连接
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }   
            }
        }
        /**
         * 6.关闭ResultSet、Statement、Connection连接。
         */
        public static void release(ResultSet rs,Statement statement,Connection conn){
            if(rs != null){
                //1.关闭数据库连接
                try {
                    rs.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }   
            }
            if(statement != null){
                //2.关闭statement对象
                try {
                    statement.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if(conn != null){
                //3.关闭数据库连接
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }   
            }
        }
        /**
         * 7.SQL注入。
         *SQL注入:利用某些系统没有对用户输入的数据进行充分的检查,而而在用户中注入非法的SQL语句段
         *或命令从而利用系统的SQL引擎完成恶意操作。
         */
        @Test
        public void testSQLinjection(){
            String username = "a' OR PASSWORD = ";
            String password = " OR '1' = '1";
            /*System.out.println("请输入账号密码:");
            Scanner input = new Scanner(System.in);
            System.out.println("账号:");
            username = input.next();
            System.out.println("密码:");
            password = input.next();*/
            String sql = "select * from user where username = '"+username
                    +"' and password = '"+password+"'";
            System.out.println(sql);
            Connection conn = null;
            Statement statement = null;
            ResultSet rs = null;
            try {
                conn = TestTools.getConnection();
                statement = conn.createStatement();
                rs = statement.executeQuery(sql);
                if(rs.next()){
                    System.out.println("登录成功!");
                }else{
                    System.out.println("登录失败!");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                TestTools.release(rs, statement, conn);
            }
        }
        /**
         * 8.使用PerparedStatement查询数据判断是否登陆成功。
         * 同时学习PerparedStatement是如何防SQL注入的。
         */
        @Test
        public void testSQLinjection1(){
            String username = "a' OR PASSWORD = ";
            String password = " OR '1' = '1";
            String sql = "select * from user where username = ? and password = ?";
            Connection conn = null;
            PreparedStatement preparedstatement = null;
            ResultSet rs = null;
            try {
                conn = TestTools.getConnection();
                preparedstatement = conn.prepareStatement(sql);
                preparedstatement.setString(1, username);
                preparedstatement.setString(2, password);
                rs = preparedstatement.executeQuery();
                if(rs.next()){
                    System.out.println("登录成功!");
                }else{
                    System.out.println("登录失败!");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                TestTools.release(rs, preparedstatement, conn);
            }
        }
    }
  • 相关阅读:
    Flink中的window、watermark和ProcessFunction(三)
    ThreadLocal刨根问底
    Flink的流处理API(二)
    Flink简介(一)
    SparkStreaming
    SparkSQL
    Spark入门
    SparkCore
    【HNOI2009】 最小圈
    【BOI 2002】 双调路径
  • 原文地址:https://www.cnblogs.com/tengpengfei/p/10454023.html
Copyright © 2011-2022 走看看