JDBC

作者: hgzzz | 来源:发表于2019-04-19 21:18 被阅读0次

    JDBC

    • JDBC:Java Database connectivity(Java数据库连接),sun公司提供的一种数据库访问规则
    • 使用方式
    1. 导入对于数据库的jar包,比如使用MySQL,就导入它的包。
    2. 编写代码
    public class MainDemo {
        public static void main(String[] args) {
            Connection conn = null;
            Statement statement = null;
            ResultSet rs = null;
    
            try {
                // 1. 注册驱动
                // DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 这样会注册两次驱动
                Class.forName("com.mysql.jdbc.Driver");
                // 2. 建立连接
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/hgzdata", "root", "root");
                // 3. 创建statement
                statement = conn.createStatement();
                // 4. 新建查询语句
                String sql = "select * from product";
                // 5. 查询数据 得到结果集
                rs = statement.executeQuery(sql);
                // 6. 处理数据
                while(rs.next()) {
                    int id = rs.getInt("pid");
                    String pname = rs.getString("pname");
                    Double price = rs.getDouble("price");
                    System.out.println("id =" + id + "; name = " + pname + "; price = " + price);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 7. 释放资源
                JDBCUtil.release(conn,statement,rs);
            }
        }
    }
    
    1. 应用,使用JUnit来测试代码
    • 工具类,负责读取数据库连接属性文件,连接数据库和释放资源
    public class JDBCUtil {
    
        static String driverClass = null;
        static String url = null;
        static String user = null;
        static String password = null;
    
        static { // 在类初始化时读取配置属性
            try {
            // 创建一个属性配置对象
            Properties properties = new Properties();
            // 获取文件的字节输入流
            // InputStream is = new FileInputStream("jdbc.properties"); // 文件输入流,文件放在工程根目录下
            InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); // 在加载类字节文件时加载通目录下的资源文件
            properties.load(is);
            // 读取属性
            driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 连接数据库
         * @return
         */
        public static Connection getConn() {
            Connection conn = null;
            // 1. 注册驱动
            // DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 这样会注册两次驱动
            try {
                Class.forName(driverClass);
                // 2. 建立连接
                conn = DriverManager.getConnection(url, user, password);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return conn;
        }
    
        /**
         * 释放资源
         * @param conn
         * @param st
         * @param rs
         */
        public static void release(Connection conn, Statement st, ResultSet rs) {
            closeRs(rs);
            closeConnection(conn);
            closeStatement(st);
        }
    
        private static void closeRs(ResultSet rs) {
            try {
                if (rs != null){
                    rs.close();
                }
    
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                rs = null;
            }
        }
    
        private static void closeStatement(Statement st) {
            try {
                if (st != null){
                    st.close();
                }
    
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                st = null;
            }
        }
    
        private static void closeConnection(Connection conn) {
            try {
                if (conn != null){
                    conn.close();
                }
    
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                conn = null;
            }
        }
    }
    
    • 查询
    @Test
    puclic void testQuery() {
            Connection conn = null;
            Statement statement = null;
            ResultSet resultSet = null;
            try {
                // 1. 获取连接对象
                conn = JDBCUtil.getConn();
                // 2. 根据连接对象得到statement
                statement = conn.createStatement();
                String sql = "select * from product";
                // 3. 执行sql语句放回数据
                resultSet = statement.executeQuery(sql);
                // 4. 处理数据
                while(resultSet.next()) {
                    System.out.println(resultSet.getInt("pid") + resultSet.getString("pname"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.release(conn, statement, resultSet);
            }
        }
    }
    
    • 插入 修改 和删除只是改变了sql
     public void testInsert() {
            Connection conn = null;
            Statement statement = null;
            ResultSet resultSet = null;
            try {
                // 1. 获取连接对象
                conn = JDBCUtil.getConn();
                // 2. 根据连接对象得到statement
                statement = conn.createStatement();
                // 3. 执行添加操作
                String sql = "insert into product values(null, 'iPhone X', 8888, 1 )";
                int result = statement.executeUpdate(sql);
                if (result > 0) {
                    System.out.println("插入成功");
                } else {
                    System.out.println("插入失败");
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.release(conn, statement);
            }
        }
    
    1. Dao(Date Access Object)模式
    • 新建一个Dao接口,定义数据库访问规则
    • 新建一个dao的实现类,具体实现早前定义的规则
    • 直接使用实现
    1. statement的安全问题
    • 先将传入的字符串拼接成sql语句,再执行,如果传入的变量中含有sql语句,就会出现安全问题。
    • PreparedStatement对象
      a. 使用该对象替换statement对象
      b. 原理:预先对 sql 语句执行语法校验,? 占用变量位置,之后不管传递什么都当成字符串处理,不会产生任何的关键字。传递是索引从 1 开始
    // 替换第二步的创建statement 对象
    String sql = "select * from user where username=? and password=?";
    PreparedStatement ps = conn.preparedStatement(sql);
    ps.setString(1, username);
    ps.setString(2, password)
    

    相关文章

      网友评论

          本文标题:JDBC

          本文链接:https://www.haomeiwen.com/subject/twzfgqtx.html