zoukankan      html  css  js  c++  java
  • 使用JDBC完成分类表CRUD的操作

     工具类

     通过之前的案例回顾,不难发现,有很多的代码操作是重复的,比如“获取链接”和“释放资源”等,将来在增删改查中经常遇到,开发中遇到这种情况,将采用工具类的方法进行抽取,从而达到代码的重复利用。

    此处使用V1版本,之后还有替他版本。

    获取链接

        /**
         * 获取连接方法
         * 
         * @return
         */
        public static Connection getConnection() {
            Connection conn = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web08", "root", "root");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return conn;
        }
    View Code

    释放资源 

        public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
        }
    View Code

     编写查询案例

     创建新的 Java 工程

    编写工具类 JDBCUtils.java

    package cn.jayvee.jdbc;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    
    /**
     * 提供获取链接和资源的方法
     * @author Jayvee
     * @date 2019-5-12 下午4:22:24
     * @version V1.0
     *
     */
    public class JDBCUtils_V1 {
    
        /**
         * 获取链接方法
         * @return
         */
        public static Connection getConnection(){
            Connection conn = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtest","root","123456");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return conn;
        }
        
        
        public static void release(Connection conn,PreparedStatement pstmt,ResultSet rs){
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (pstmt!=null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
    }

     编写测试类 TestUtils.java

    package cn.jayvee.test;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import org.junit.Test;
    
    import cn.jayvee.jdbc.JDBCUtils_V1;
    
    /**
     * 测试工具类
     * 
     * @author Jayvee
     * @date 2019-5-12 下午4:38:54
     * @version V1.0
     */
    public class TestUtils {
    
        /**
         * 根据id查询用户信息
         */
        @Test
        public void testFindUserById() {
            Connection conn = null;
            ResultSet rs = null;
            PreparedStatement pstmt = null;
            try {
                // 1.获取链接
                conn = JDBCUtils_V1.getConnection();
                // 2.编写sql语句
                String sql = "select * from student where id=?";
                // 3.获取执行sql语句对象
                pstmt = conn.prepareStatement(sql);
                // 4.设置参数(1表示第一个问号,2表示第一个问号的值是2)
                pstmt.setInt(1, 2);
                // 5.执行查询操作
                rs = pstmt.executeQuery();
                // 6.处理结果集
                while (rs.next()) {
                    // rs.getString(2)表示获取这条数据的第二列的数据
                    // rs.getString("age")表示获取这条数据中age字段的之
                    System.out.print(rs.getString(2) + "----" + rs.getString("age"));
                }
                // 释放资源放在这里不可行!
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                // 7.释放资源
                JDBCUtils_V1.release(conn, pstmt, rs);
            }
        }
    
    }

     数据库数据

       

    运行结果

      

    使用 Properties 配置文件

      开发中获得链接的四个参数(驱动、URL、用户名、密码)通常都存在在配置文件中,方便后期维护,程序如果需要更换数据库,只需要修改配置文件即可。

    通常情况下,我们习惯使用 properties 文件,此文件我们将作如下要求:

      1. 文件位置:任意,建议src下。

      2. 文件名称:任意,扩展名为 properties 。

      3. 文件内容:一行一组数据,格式是“ key = value ”。

        a)key 命名自定义,不能带有空格,如果是多个单词,习惯使用点分隔。例如“ jdbc.driver ”

        b)value值不支持中文,不能带有空格,如果需要使用非英文字符,将进行 Unicode 转换。

    项目练习

    在 src 目录下创建一个 db.properties 配置文件。

      

    文件内编写如下配置(具体情况具体改)

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/dbtest?useUnicode=true&characterEncoding=utf8
    username=root
    password=123456

    加载配置文件:ResourceBundle 对象

      我们在V2版本中使用JDK提供的工具类 ResourceBundle 加载 properties 文件,ResourceBundle 提供 getBundle() 方法用于只提供 properties 文件即可,之后使用 getString(key) 通过 key 获得 value的值。

    编写代码案例 

    创建一个JDBCUitls_V2.java 工具类

      

    编写内容

    package cn.jayvee.jdbc;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ResourceBundle;
    
    
    /**
     * 提供获取链接和资源的方法
     * @author Jayvee
     * @date 2019-5-12 下午4:22:24
     * @version V1.0
     *
     */
    public class JDBCUtils_V2 {
        
        private static String driver;
        private static String url;
        private static String username;
        private static String password;
        
        /**
         * 静态代码块加载配置文件信息
         */
        static{
            // 加载配置文件
            ResourceBundle bundle = ResourceBundle.getBundle("db");
            driver = bundle.getString("driver");
            url = bundle.getString("url");
            username = bundle.getString("username");
            password = bundle.getString("password");
        }
    
        /**
         * 获取链接方法
         * @return
         */
        public static Connection getConnection(){
            Connection conn = null;
            try {
                Class.forName(driver);
                conn = DriverManager.getConnection(url,username,password);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return conn;
        }
        
        
        /**
         * 释放资源
         * @param conn
         * @param pstmt
         * @param rs
         */
        public static void release(Connection conn,PreparedStatement pstmt,ResultSet rs){
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (pstmt!=null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

     编写 TestUtils.java 文件

    package cn.jayvee.test;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import javax.management.RuntimeErrorException;
    
    import org.junit.Test;
    
    import cn.jayvee.jdbc.JDBCUtils_V1;
    import cn.jayvee.jdbc.JDBCUtils_V2;
    
    /**
     * 测试工具类
     * 
     * @author Jayvee
     * @date 2019-5-12 下午4:38:54
     * @version V1.0
     */
    public class TestUtils {
    
        
        /**
         * 添加用户信息方法
         */
        @Test
        public void testAdd(){
            Connection conn = null;
            PreparedStatement pstmt = null;
            try {
                // 1.获取连接
                conn = JDBCUtils_V2.getConnection();
                // 2.编写 sql 语句
                String sql = "insert into student values(null,?,?)";
                // 3.获取执行sql语句对象
                pstmt = conn.prepareStatement(sql);
                // 4.设置参数
                pstmt.setString(1, "wangjiawei");
                pstmt.setString(2, "25");
                // 5.执行插入操作
                int row = pstmt.executeUpdate();
                if (row>0) {
                    System.out.println("添加成功!");
                }else{
                    System.out.println("添加失败!");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally{
                // 6.释放资源
                JDBCUtils_V2.release(conn, pstmt, null);
            }
        }
        
        /**
         * 根据id查询用户信息
         */
        public void testFindUserById() {
            Connection conn = null;
            ResultSet rs = null;
            PreparedStatement pstmt = null;
            try {
                // 1.获取链接
                conn = JDBCUtils_V1.getConnection();
                // 2.编写sql语句
                String sql = "select * from student where id=?";
                // 3.获取执行sql语句对象
                pstmt = conn.prepareStatement(sql);
                // 4.设置参数(1表示第一个问号,2表示第一个问号的值是2)
                pstmt.setInt(1, 2);
                // 5.执行查询操作
                rs = pstmt.executeQuery();
                // 6.处理结果集
                while (rs.next()) {
                    // rs.getString(2)表示获取这条数据的第二列的数据
                    // rs.getString("age")表示获取这条数据中age字段的之
                    System.out.print(rs.getString(2) + "----" + rs.getString("age"));
                }
                // 释放资源放在这里不可行!
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                // 7.释放资源
                JDBCUtils_V1.release(conn, pstmt, rs);
            }
        }
    
    }

       

      

    加载配置文件:Properties 对象

       对应 properties 文件的处理,开发中也会使用 Properties 对象将进行,在V3版本中,我们将采用加载 properties 文件获得流,然后使用 properties 对象进行处理。

    创建一个JDBCUitls_V3.java 工具类

       

    编写内容

    package cn.jayvee.jdbc;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    /**
     * 提供获取链接和资源的方法
     * 
     * @author Jayvee
     * @date 2019-5-12 下午4:22:24
     * @version V1.0
     * 
     */
    public class JDBCUtils_V3 {
    
        private static String driver;
        private static String url;
        private static String username;
        private static String password;
    
        /**
         * 静态代码块加载配置文件信息
         */
        static {
            try {
                // 1.通过当前类获取类加载器
                ClassLoader classLoader = JDBCUtils_V3.class.getClassLoader();
                // 2.通过类加载器的方法获取一个输入流
                InputStream is = classLoader.getResourceAsStream("db.properties");
                // 3.创建一个properties对象
                java.util.Properties props = new java.util.Properties();
                // 4.加载输入流
                props.load(is);
                // 5.获取相关参数的值
                driver = props.getProperty("driver");
                url = props.getProperty("url");
                username = props.getProperty("username");
                password = props.getProperty("password");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 获取链接方法
         * 
         * @return
         */
        public static Connection getConnection() {
            Connection conn = null;
            try {
                Class.forName(driver);
                conn = DriverManager.getConnection(url, username, password);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return conn;
        }
    
        /**
         * 释放资源
         * 
         * @param conn
         * @param pstmt
         * @param rs
         */
        public static void release(Connection conn, PreparedStatement pstmt,
                ResultSet rs) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    
    }

    在 TestUtils.java 中编写删除方法

    package cn.jayvee.test;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import javax.management.RuntimeErrorException;
    
    import org.junit.Test;
    
    import cn.jayvee.jdbc.JDBCUtils_V1;
    import cn.jayvee.jdbc.JDBCUtils_V2;
    import cn.jayvee.jdbc.JDBCUtils_V3;
    
    /**
     * 测试工具类
     * 
     * @author Jayvee
     * @date 2019-5-12 下午4:38:54
     * @version V1.0
     */
    public class TestUtils {
    
        
        /**
         * 根据id删除信息
         */
        @Test
        public void testDeleteById(){
            Connection conn = null;
            PreparedStatement pstmt = null;
            try {
                // 1.获取连接
                conn = JDBCUtils_V3.getConnection();
                // 2.编写 sql 语句
                String sql = "delete from student where id=?";
                // 3.获取执行sql语句对象
                pstmt = conn.prepareStatement(sql);
                // 4.设置参数
                pstmt.setInt(1, 3);
                // 5.执行删除操作
                int row = pstmt.executeUpdate();
                if (row>0) {
                    System.out.println("删除成功!");
                }else{
                    System.out.println("删除失败!");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally{
                // 6.释放资源
                JDBCUtils_V3.release(conn, pstmt, null);
            }
        }
        
        
        
        /**
         * 添加用户信息方法
         */
        public void testAdd(){
            Connection conn = null;
            PreparedStatement pstmt = null;
            try {
                // 1.获取连接
                conn = JDBCUtils_V2.getConnection();
                // 2.编写 sql 语句
                String sql = "insert into student values(null,?,?)";
                // 3.获取执行sql语句对象
                pstmt = conn.prepareStatement(sql);
                // 4.设置参数
                pstmt.setString(1, "wangjiawei");
                pstmt.setString(2, "25");
                // 5.执行插入操作
                int row = pstmt.executeUpdate();
                if (row>0) {
                    System.out.println("添加成功!");
                }else{
                    System.out.println("添加失败!");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally{
                // 6.释放资源
                JDBCUtils_V2.release(conn, pstmt, null);
            }
        }
        
        /**
         * 根据id查询用户信息
         */
        public void testFindUserById() {
            Connection conn = null;
            ResultSet rs = null;
            PreparedStatement pstmt = null;
            try {
                // 1.获取链接
                conn = JDBCUtils_V1.getConnection();
                // 2.编写sql语句
                String sql = "select * from student where id=?";
                // 3.获取执行sql语句对象
                pstmt = conn.prepareStatement(sql);
                // 4.设置参数(1表示第一个问号,2表示第一个问号的值是2)
                pstmt.setInt(1, 2);
                // 5.执行查询操作
                rs = pstmt.executeQuery();
                // 6.处理结果集
                while (rs.next()) {
                    // rs.getString(2)表示获取这条数据的第二列的数据
                    // rs.getString("age")表示获取这条数据中age字段的之
                    System.out.print(rs.getString(2) + "----" + rs.getString("age"));
                }
                // 释放资源放在这里不可行!
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                // 7.释放资源
                JDBCUtils_V1.release(conn, pstmt, rs);
            }
        }
    
    }

      

        

    在 TestUtils.java 中编写更新方法

    package cn.jayvee.test;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    
    import org.junit.Test;
    
    import cn.jayvee.jdbc.JDBCUtils_V1;
    import cn.jayvee.jdbc.JDBCUtils_V2;
    import cn.jayvee.jdbc.JDBCUtils_V3;
    
    /**
     * 测试工具类
     * 
     * @author Jayvee
     * @date 2019-5-12 下午4:38:54
     * @version V1.0
     */
    public class TestUtils {
    
        
        /**
         * 根据id更新信息
         */
        @Test
        public void testUpdateById(){
            Connection conn = null;
            PreparedStatement pstmt = null;
            try {
                // 1.获取连接
                conn = JDBCUtils_V3.getConnection();
                // 2.编写 sql 语句
                String sql = "update student set age=? where id=?";
                // 3.获取执行sql语句对象
                pstmt = conn.prepareStatement(sql);
                // 4.设置参数
                pstmt.setInt(1, 18);
                pstmt.setInt(2, 1);
                // 5.执行更新操作
                int row = pstmt.executeUpdate();
                if (row>0) {
                    System.out.println("更新成功!");
                }else{
                    System.out.println("更新失败!");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally{
                // 6.释放资源
                JDBCUtils_V3.release(conn, pstmt, null);
            }
        }
        
        
        /**
         * 根据id删除信息
         */
        public void testDeleteById(){
            Connection conn = null;
            PreparedStatement pstmt = null;
            try {
                // 1.获取连接
                conn = JDBCUtils_V3.getConnection();
                // 2.编写 sql 语句
                String sql = "delete from student where id=?";
                // 3.获取执行sql语句对象
                pstmt = conn.prepareStatement(sql);
                // 4.设置参数
                pstmt.setInt(1, 3);
                // 5.执行删除操作
                int row = pstmt.executeUpdate();
                if (row>0) {
                    System.out.println("删除成功!");
                }else{
                    System.out.println("删除失败!");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally{
                // 6.释放资源
                JDBCUtils_V3.release(conn, pstmt, null);
            }
        }
        
        
        
        /**
         * 添加用户信息方法
         */
        public void testAdd(){
            Connection conn = null;
            PreparedStatement pstmt = null;
            try {
                // 1.获取连接
                conn = JDBCUtils_V2.getConnection();
                // 2.编写 sql 语句
                String sql = "insert into student values(null,?,?)";
                // 3.获取执行sql语句对象
                pstmt = conn.prepareStatement(sql);
                // 4.设置参数
                pstmt.setString(1, "wangjiawei");
                pstmt.setString(2, "25");
                // 5.执行插入操作
                int row = pstmt.executeUpdate();
                if (row>0) {
                    System.out.println("添加成功!");
                }else{
                    System.out.println("添加失败!");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally{
                // 6.释放资源
                JDBCUtils_V2.release(conn, pstmt, null);
            }
        }
        
        /**
         * 根据id查询用户信息
         */
        public void testFindUserById() {
            Connection conn = null;
            ResultSet rs = null;
            PreparedStatement pstmt = null;
            try {
                // 1.获取链接
                conn = JDBCUtils_V1.getConnection();
                // 2.编写sql语句
                String sql = "select * from student where id=?";
                // 3.获取执行sql语句对象
                pstmt = conn.prepareStatement(sql);
                // 4.设置参数(1表示第一个问号,2表示第一个问号的值是2)
                pstmt.setInt(1, 2);
                // 5.执行查询操作
                rs = pstmt.executeQuery();
                // 6.处理结果集
                while (rs.next()) {
                    // rs.getString(2)表示获取这条数据的第二列的数据
                    // rs.getString("age")表示获取这条数据中age字段的之
                    System.out.print(rs.getString(2) + "----" + rs.getString("age"));
                }
                // 释放资源放在这里不可行!
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                // 7.释放资源
                JDBCUtils_V1.release(conn, pstmt, rs);
            }
        }
    
    }

     

    项目代码https://github.com/wjw1014/JavaMysqlStudy/tree/master/web09 (小白操作,仅供参考!)

  • 相关阅读:
    基于VLC的视频播放器
    IOS开发之新浪微博OAuth2
    Android之官方导航栏ActionBar
    IOS中键盘隐藏几种方式
    在Android中使用Android Ksoap2调用WebService
    Android之属性动画(二)
    IOS 内存管理
    利用scp 远程上传下载文件/文件夹和ssh远程执行命令
    Centos 检查磁盘读写性能
    JPA, JNDI, OSGi
  • 原文地址:https://www.cnblogs.com/wjw1014/p/10852834.html
Copyright © 2011-2022 走看看