工具类TestTools

来源:互联网 发布:赣州淘宝培训 编辑:程序博客网 时间:2024/06/03 02:26

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

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);        }    }}
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 小米笔记本忘记开机密码怎么办 小米手机儿童模式忘记密码怎么办 小米应用锁密码忘了怎么办 小米air密码忘了怎么办 小米4密码忘了怎么办 小米手机开机密码忘了怎么办? 小米笔记本电脑开机密码忘了怎么办 小米笔记本开机密码忘了怎么办 htc手机忘记解锁图案怎么办 红米手机屏幕锁定怎么解锁怎么办 小米5s有id怎么办 手机密码找不回来了怎么办? 手机密码图案忘了怎么办 手机屏幕图案锁忘了怎么办 捡到苹果7有id锁怎么办 魅族什么都忘了怎么办 海信电视百事通登陆失败怎么办 去哪儿换号了怎么办 ipan充不进去电怎么办 安卓数据线松了怎么办 索尼z5耳机掉漆怎么办 索尼z5无限重启怎么办 苹果8基带坏了怎么办 oppo手机忘记图案密码怎么办 电池充不进去电怎么办 电脑充不进去电怎么办 苹果5c白苹果怎么办 港行不支持电信卡怎么办 安卓导航不开机怎么办 鞭炮放一半不响怎么办 禁止鸣笛的地方鸣笛了怎么办 手被炮仗炸了怎么办 手被猴子抓伤了怎么办 炸东西剩的油怎么办 炸臭豆腐剩的油怎么办 油炸久了油发黑怎么办 炸鱼的时候粘锅怎么办 吃了葱蒜有味怎么办 哺乳期喝了抹茶怎么办 干炸小黄鱼凉了怎么办 烧鱼酱油放多了怎么办