A taste of JDBC - How does JAVA use the simplest method to connect to the database

written in front

Although various frameworks are emerging in an endless stream, they perfectly provide more convenient APIs for operating databases.
But for beginners to practice SQL syntax, or master a little basic JDBC usage, and apply it to some small projects that they do for fun, JDBC is still worth learning.
insert image description here

1. Unified database interface JDBC

•JDBC (Java DataBase Connectivity), that is, java database connection, is a Java API for executing SQL statements, which can provide unified access to various relational databases. It consists of a set of classes and interfaces written in Java language. JDBC provides a baseline from which higher-level tools and interfaces can be built to enable database developers to write database applications.

JDBC core components:

  1. DriverManager: driver manager, matching according to the connection identifier and the specific database driver

  2. Driver: According to the loaded Class information, it is generated and deployed by the manager, and generally not used directly

  3. Connection: Represents an object specifically connected to a database

  1. Statement: Use objects created from this interface to submit SQL statements to the database

insert image description here

  1. ResultSet: These objects hold the data retrieved from the database after executing SQL queries using Statement objects

insert image description here

  1. SQLException: This class handles any error that occurs in the database application

2. How to use (main part)

  • Preliminary preparation (note here that the mysql-connector-java library needs to be imported)

insert image description here

  • SQL execution

  • File directory and table creation txt

insert image description here

3. Code

//文件IO
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
//sql支持
import java.sql.*;
//集合框架,List
import java.util.List;

public class MySQLDemo {
    
    

    //数据库连接基本信息
    //数据库驱动,提供对相应数据库操作支持
    //低版本去掉.cj
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    //数据库地址,用户名和密码
    static final String DB_URL = "jdbc:mysql://localhost:3306/MySQLDemoTest?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
    static final String USER = "root";
    static final String PASS = "123";

    public static void main(String[] args) {
    
    
        //使用url和用户名密码建立连接
        Connection conn = null;
        //Statement 是 Java 执行数据库操作的一个重要接口,用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句
        Statement stmt = null;

        Path pathCreat= Paths.get("src","MySQL","target","classes","CreatTable.txt");

        try{
    
    
            // 注册 JDBC 驱动;载入Class文件信息
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            //建立好连接后,获取当前连接的Statement对象
            System.out.println("实例化Statement对象...");
            stmt = conn.createStatement();

            //读取pathCreat目录下的文件内容,组成SQL语句
            StringBuffer sql=new StringBuffer();
            List<String> list=Files.readAllLines(pathCreat.toAbsolutePath());
            for(String m:list)
                sql.append(m);

            //通过Statement的对象执行String类型的SQL语句即可
            System.out.println("删除表...");
            stmt.executeUpdate("DROP TABLE IF EXISTS student;");

            System.out.println("新建表...");
            stmt.executeUpdate(sql.toString());

            System.out.println("插入...");
            for(int i=1;i<10;i++)
            stmt.executeUpdate("INSERT INTO student (name) VALUES('呆瓜"+i+"号')");

            System.out.println("查询...");
            ResultSet rs = stmt.executeQuery("SELECT * FROM student");

            // 展开结果集数据库
            while(rs.next()){
    
    
                // 通过字段检索
                int id  = rs.getInt("id");
                String name = rs.getString("name");

                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 姓名: " + name);

                System.out.print("\n");
            }

            System.out.println("删除...");
            for(int i=1;i<10;i++){
    
    
                if(i%2==0){
    
    
                    stmt.executeUpdate("DELETE FROM student\n" +
                            "WHERE id="+i+"; ");
                }
            }

            System.out.println("删除后查询...");
            rs = stmt.executeQuery("SELECT * FROM student");

            while(rs.next()){
    
    
                // 通过字段检索
                int id  = rs.getInt("id");
                String name = rs.getString("name");

                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 姓名: " + name);
                System.out.print("\n");
            }

            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
    
    
            // 处理 JDBC 错误
            se.printStackTrace();
        }catch(Exception e){
    
    
            // 处理 Class.forName 错误
            e.printStackTrace();
        }finally{
    
    
            // 关闭资源
            try{
    
    
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
    
    
            }// 什么都不做
            try{
    
    
                if(conn!=null) conn.close();
            }catch(SQLException se){
    
    
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

4. Other introductions

Database development period:

• No-database era: There is no dedicated database, and most data is stored in the form of files

• Hierarchical database: use hierarchical model for database design and storage

•Network database: use the network model for database design and storage

• Relational database: use relational model for database design and storage

•Non-relational database: In order to adapt to horizontal scalability and handle a large amount of data environment, it has developed very rapidly in recent years, and there are many derivative types

New challenges and applications:

•Although in the current era of Web 2.0—user interaction and co-construction put forward higher requirements for database reading and writing, a large amount of data needs to be saved, and thus NoSQL databases suitable for different fields were born

• However, relational databases still occupy a dominant position, and with continuous development and learning from others, relational databases will also usher in a more brilliant new stage - NewSQL

Guess you like

Origin blog.csdn.net/caqjeryy/article/details/123960099