java学习笔记—JDBC1(16)

1、数据持久化

l  持久化(persistence):把数据保存到可掉电式存储设备中以供之后使用,也称为“固化”。在大多数情况下,服务器或客户端应用中数据的持久化是通过关系型数据库来实现

l  存储设备:磁盘、硬盘, U盘,光盘等

l  存储形式:数据库、xml文件、txt文件等

2、知识点2: Java 中的数据存储技术

l  在Java中,数据库存取技术可分为如下几类:

l  JDBC直接访问数据库

l  第三方O/R工具,如Hibernate, ibatis 等

l  JDBC是java访问数据库的基石,其他技术都是对jdbc的封装

3、什么是JDBC

l  JDBC(Java Database Connectivity)是一个独立于特定数据库管理系统、通用的操作数据库的Interface(一组API),定义了用来访问数据库的标准Java类库,而接口的实现有各个数据库厂商来完成

l  JDBC驱动程序(jar包):数据库厂商对JDBC接口的一组实现类(jar包)

4、什么是ODBC

l  ODBC(Open Database Connectivity,开放数据库连接)是微软公司开放服务结构中有关数据库的一个组成部分,它建立了一组规范,并提供了一组对数据库访问的标准API

5、JDBC的分类

目前有四种可供使用的JDBC驱动程序,不同类型的的驱动程序有着不一样的使用方法,所以当我们在连接数据库之前,必须先依照我们的需求选择一个适当的驱动程序,这四种不同类型的驱动程序分别是:

   1  JDBC-ODBC桥 :桥接器型的驱动程序,

   2   部分本地API部分Java的驱动程序,也是桥接器型驱动程序之一

   3   JDBC网络纯Java驱动程序

   4   本地协议的纯 Java 驱动程序:这类型的驱动程序是最成熟的JDBC驱动程序,不但无需在使用者计算机上安装任何额外的驱动程序,也不需在服务器端安装任何的中介程序(middleware),所有存取数据库的操作,都直接由驱动程序来完成。

6、JDBC API接口介绍

7、java初体验

 // 1.数据库服务开启。 2.需要将数据库驱动导入.

//JDBC体验

public class Test1 {  
    public static void main(String[] args) throws Exception {
        //1.将驱动进行注册(可以进行与数据库的链接)        
        DriverManager.registerDriver(new Driver());
        //2.得到一个与数据库连接的对象
        Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb","root","root");
        //3.得到一个执行sql对象
        Statement stm=con.createStatement();
        //4.执行sql语句. 以查询为例,执行后会返回一个ResultSet结果集。(其实就是包含查询到的信息)
        ResultSet rs=stm.executeQuery("select * from emp");  //查表名
        //5.将结果集中的内容迭代出来.
        while(rs.next()){
            Object obj=rs.getObject("ename");   //查列名
            System.out.println(obj);
        }
        //6.需要将资源释放
        rs.close();
        stm.close();
        con.close();    }
}  

8、对以上代码进行异常处理:   

//JDBC异常处理
public class Test3 {
    public static void main(String[] args) {
        Connection con = null;
        Statement stm = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/mydb", "root", "root");
            stm = con.createStatement();
            rs = stm.executeQuery("select * from emp");
            while (rs.next()) {
                String name = rs.getString("ename");
                int no = rs.getInt("empno");
                Date date = rs.getDate("hiredate");
                System.out.println(name + " " + no + " " + date);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("加载驱动失败");
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("SQL操作失败");
        } finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭rs失败的");
            }
            try {
                if (stm != null)
                    stm.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭stm失败的");
            }
            try {
                if (con != null)
                    con.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭con失败的");
            }
        }
    }
}

9、对以上代码进行优化(1)

public class Test4 {
    @Test
    public void jdbcTest() {
        //定义在外面,同时将处理异常方法定义在外面
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1:3306/mydb";
        String username = "root";
        String password = "root";
        Connection con = null;
        Statement stm = null;
        ResultSet rs = null;
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
            stm = con.createStatement();
            rs = stm.executeQuery("select * from emp");
            while (rs.next()) {
                String name = rs.getString("ename");
                int no = rs.getInt("empno");
                Date date = rs.getDate("hiredate");
                System.out.println(name + " " + no + " " + date);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("加载驱动失败");
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("SQL操作失败");
        } finally {
            closeResultSet(rs);
            closeStatment(stm);
            closeConnection(con);
        }
    }
    // 关闭Connection
    // 关闭的Statement
    // 关闭ResultSet方法
    public void closeConnection(Connection con) {
        try {
            if (con != null)
                con.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭con失败的");
        }
    }
    public void closeStatment(Statement stm) {
        try {
            if (stm != null)
                stm.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭stm失败的");
        }
    }
    public void closeResultSet(ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭rs失败的");
        }
    }
}

10 对以上代码再次优化

10.1 定义一个mysqldb.properties配置文件

定义好配置变量  

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/testguest
username=root
password=1234abcd

10.2 新建jdbcUtil工具类 JdbcUtil.cs

 获取配置文件中的值

private static String driver;
    private static String url;
    private static String username;
    private static String password;
    // 对driver,url,username, password 进行赋值
    static {
        // 通过类加载器获得资源,并以流的方式进行操作
        InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream(
                "包名/ db.properties");
        Properties prop = new Properties();
        try {
            prop.load(is);
            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("读取数据库配置文件失败");
        }
    }

 10.2.1 加载驱动

static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("加载驱动失败");
        }
    }

10.2.2获得连接的方法

public static Connection getConnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("连接数据库操作失败");
        } finally {
        }
        return con;
    }

 10.2.3 关闭的方法

// 关闭Connection
    // 关闭的Statement
    // 关闭ResultSet方法
    public static void close(Connection con) {
        try {
            if (con != null)
                con.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭con失败的");
        }
    }
    public static void close(Statement stm) {
        try {
            if (stm != null)
                stm.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭stm失败的");
        }
    }
    public static void close(ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭rs失败的");
        }
    }

10.3 新建Test.CS类

public class Test {
    
    @Test
    public void select() {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            con = JdbcUtil.getConnection();
            st = con.createStatement();
            rs = st.executeQuery("select * from tg_user");
            while (rs.next()) {
                System.out.println(rs.getInt(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(rs);
            JdbcUtil.close(st);
            JdbcUtil.close(con);
        }
    }
}
原文地址:https://www.cnblogs.com/zhenghongxin/p/4372907.html