Acquaintance JDBC- a chapter

A, JDBC Overview

1. What is JDBC

  • Is a Java API for executing SQL statements for
  • It consists of a set of classes written in the Java language and interfaces
  • JDBC provides a standard method of operating a data
  • JDBC goal is to make Java programmers can connect to any JDBC driver provides a JDBC database system

2. drive connection


java.sql package is the JDBC API. The major database vendors will provide implementation classes for the JDBC API driver package. Be careful not to mistake the lead pack, do not refer to this class not to introduce com.mysql..Xxx

Second, connect to MySQL

Connection is divided into two steps, the first step is to load the driver, the second step to establish connections to obtain a connection object. Since I use the MySQL database is so only introduce MySQL connection. After the experience of MySQL upgrade is now divided into two drive connections. Specific may see this blog https://www.cnblogs.com/NyanKoSenSei/p/11510438.html. Since I am using MySQL8 so here lists only 5+ connection method

public static void main(String[] args) throws Exception {
        //1.加载驱动
        //把com.mysql.jdbc.Driver这份字节码加载进JVM
        //当一份字节码被加载到JVM时,就会执行该字节码中的静态代码块
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接对象
        //url数据库地址
        String url = "jdbc:mysql://localhost:3306/promission?serverTimezone=UTC&characterEncoding=utf-8";
        //用户名
        String user = "root";
        //密码
        String password = "123456";
        //获取连接对象
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }

java 1.6 After the first step may not be needed to load the write driver, java file automatically FIG loaded into this JVM byte code. But if it is done javaweb development must be coupled with the first step, javaweb not load this byte code automatically.

三、DDL&DML

After connecting to change how we build a database table, insert it?

  1. Sql statement to create objects with string
  2. Create a Statement interface for performing a static sql statement object
  3. SQL statements sent to the database to execute and return the result. For DQL query returns a result set for DML returns the number of rows affected for DDL returns 0.
  4. executeUpate (String) to perform DML and DDL statements
  5. Close Resources
        //编写sql语句
        String  s = "create table stu(id int, age int, name varchar(20))";
        Statement st = conn.createStatement();
        //执行sql
        int row = st.executeUpdate(s);
        //关闭资源
        st.close();
        conn.close();

Why do I need to release resources?

Connection connection is equivalent to establish a pipeline between Java and Mysql. Only connected to the data connection, Statement equivalent from the database and then execution of the program a pipe connection Mysql. On the following chart general, so after the release of the resources we need to use a level.

我们已经大致了解了如何利用jdbc操纵数据库,上面代码都直接将异常抛出了,但实际中我们不能这么做所以下面提供较为完整的代码

public static void main(String[] args) {

        Connection conn = null;
        Statement st = null;
        try {
            // 1.加载驱动
            // 把com.mysql.jdbc.Driver这份字节码加载进JVM
            // 当一份字节码被加载到JVM时,就会执行该字节码中的静态代码块
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获取连接对象
            // url数据库地址
            String url = "jdbc:mysql://localhost:3306/jdbc_db?serverTimezone=UTC&characterEncoding=utf-8";
            // 用户名
            String user = "root";
            // 密码
            String password = "123456";
            // 获取连接对象
            conn = DriverManager.getConnection(url, user, password);
            // 3.编写sql语句
            String s = "insert into stu(id, age, name)values(001, 20, 'xiaoming')";
            st = conn.createStatement();
            // 4.执行sql
            int row = st.executeUpdate(s);
            System.out.println(row);

        } catch (Exception e) {

        } finally {
            // 5.关闭资源
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

    }

三、查询(DQL)

查询操作与上面类似,只是查询操作使用的是executeQuery(Sql)方法返回的是一个结果集(ResultSet)并不是像上面一般返回一个值。结果集中表示的是数据库查询的结果的集合,在执行查询语句时就会得到一个这样的结果。

查询常用方法有:

  • boolean next():判断是否有下一行数据,若有,则向下移动一行指针.
  • getXxx(int columnIndex):获取当前行中,第几列.(从1开始):不推荐
  • getXxx(String columnName):获取当前行中的,指定列名的列的值.columnName是列名/列的别名
  • 若列的类型是VARCHAR/CHAR/TEXT,都使用getString来获取列的值.
  • 若列的类型是int/integer/-->getInt来获取列的值.
  • executeQuery(Sql)会得到一个结果集

下图是java-MySQL常用数据类型对照表

下面列出一次查询多条数据的代码,异常全部抛出方便阅读:

public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/jdbc_db?serverTimezone=UTC&characterEncoding=utf-8";
        String user = "root";
        String pwd = "123456";
        Connection conn = DriverManager.getConnection(url, user, pwd);
        
        String sql = "SELECT * FROM stu;";
        Statement st = conn.createStatement();
        ResultSet set = st.executeQuery(sql);
        while(set.next()) {
            int id = set.getInt("id");
            int age = set.getInt("age");
            String name = set.getString("name");
            System.out.println("id = "+id+" age = "+age+" name = "+name);
        }
        st.close();
        conn.close();
    }

四、DAO

1.什么是DAO

我们在前面可以发现,每次我们访问数据库都需要重复的写加载驱动、连接语句等等。这样会产生许多的重复代码,并且十分的不方便。所以DAO便应运而生了。什么是DAO?DAO全称Data Access Object(数据存取对象),位于业务逻辑(test)和持久化数据(DB)之间实现对持久化数据的访问。以后我们程序便是通过DAO进行访问数据库,通过DAO提供的操作进行对数据库的访问、修改。

2.ORM

在进行DAO设计前我们先需要了解ORM。什么是ORM?ORM是对象关系映射,将关系数据库中表中的记录映射成为对象,以对象的形式展现,因此ORM的目的是为了方便开发人员以面向对象的思想来实现对数据库的操作。对应关系如下图所示

具体的一个代码例子如下:

3.domain

了解完ORM接下来我们还需要了解domain。那么什么是domain?domain就是一类类,这个类符合JavaBean规范(一个类当中有字段和该字段的getter与Setter方法)。domain的作用是用户与数据库交互的核心中转站。正如我们上面提到的ORM一般,domain其实就是orm加上getter与setter方法。

一个domain类如下图所示:

如何使用domain保存数据?见下图

在此图中我们很容易可以看出,通过对Stu类(domain)的一个对象s进行赋值,然后将s传入DAO层,在DAO层中解析s对象,取出对象中的数据,将数据拼接成sql语句然后对DB进行操作。

如何使用domain获取数据?见下图

在此图中我们表示了domain如何从DB中获取数据,在test1我们想要获取id = 1的记录,所以我们利用DAO层中的getStu(id)方法查询DB,将DB返回给我们的结果封装到一个Stu对象中,最后返回这个对象给test1。

END...

Guess you like

Origin www.cnblogs.com/ThinMoon/p/12302911.html