【一】JDBC核心技术

1、什么是JDBC

  Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。我们通常说的JDBC是面向关系型数据库的。——百度百科

  JDBC的主要作用并不只是连接数据库,更加强大的功能在于,只要数据库支持SQL语句,就可以使用JDBC技术在Java语言中执行SQL语句,从而达到与数据库进行通信的目的。

  JDBC还可以获取数据库、数据表及其数据库对象的基本信息,但其最常使用的功能还是对数据库进行增删改查操作。

2、为什么要使用JDBC

  首先我们来了解下数据库概念:  

  数据库是“按照数据结构来组织、存储和管理数据的仓库”。是一个长期存储在计算机内的、有组织的、可共享的、统一管理的大量数据的集合。
  简单来说,数据库本身可视为电子化的文件柜——存储电子文件的处所,用户可以对文件中的数据进行新增、截取、更新、删除等操作。
  严格来说,数据库是长期储存在计算机内、有组织的、可共享的数据集合。数据库中的数据指的是以一定的数据模型组织、描述和储存在一起、具有尽可能小的冗余度、较高的数据独立性和易扩展性的特点并可在一定范围内为多个用户共享。
  常见的数据库:DB2、Oracle、Informix、Sybase、SQL Server、PostgreSQL、mySQL、access、mongodb
 
  假设有三种主流的数据库产品,分别为A、B和C。我们现在想用Java语言去操作这些数据库,但出现了一个重要的问题:Java是Sun公司设计的程序开发语言,而Oracle是甲骨文公司设计的数据库产品,在通常情况下,使用A厂商的程序语言去操作B厂商的数据库是不可能的事情。想要解决这一难题,可以参考以下两种途径。
  (1)B厂商提供数据库的源代码给A厂商,A厂商通过数据库的源代码来分析如何与B厂商的数据库进行通信。但开放数据库的源代码除了MySQL,其他的厂商由于商业利益等原因是不可能做到的,所以让B厂商开放源代码难以实现。
  (2)B厂商不需要公开数据库的源代码,而是自行设计Java类库并结合自家数据库产品的通信协议实现利用Java操作数据库。由于数据库系统的通信协议是相当私密的技术内容,因此这三个数据库厂商分别根据自己的数据库产品提供了操作数据库的私有Java API类库。这些私有API都是数据库厂商提供的,程序员使用它们就可以操作这三种数据库了。
  但是问题出现了:程序员必须要学习三种数据库的Java API才能对这三种数据库进行操作,这给程序员带来极大的学习成本,也给项目在数据库移植时带来很大的不便,
  Sun公司发现了这个问题,并发布了一个标准来解决这个问题,它就是JDBC。
 
  总结一下什么是JDBC:
  (1)JDBC是Sun公司为统一操作数据库而发布的以恶搞标准,并未这个标准定义了一套使用Java操作数据库的API。
  (2)使用JDBC可以执行SQL语句。
  (3)JDBC由一组使用Java语言定义的接口和类组成,程序员需要学习这些接口和类。
  (4)JDBC是Java语言与数据库之间通信的桥梁。  
  (5)JDBC是众多ORM框架的基础,比如Hibernate, MyBatis等框架,内部的原理都是基于JDBC的。
  (6)JDBC属于JavaEE规范中的一种。
  (7)开发JDBC程序需要使用java. sql和javax. sql包中的APl。

  简单地说,JDBC可做三件事:
  (1)与数据库建立连接。
  (2)发送操作数据库的SQL语句。
  (3)获得返回的数据。

 

3、什么是JDBC驱动

  简单来讲,JDBC驱动是一个以.jar为拓展名的包,由数据库厂商提供,它们清楚如何用Java连接到本公司的数据库产品,重点是.class中的部分文件实现了JDBC规范中的接口,从而我们可以使用类似于下面的JDBC代码对数据库进行操作:

JDBC的标准接口对象 = new jar包文件中的实现类();

   由于jar包文件中的类实现了JDBC的标准接口,属于实现关系,也是多态关系,所以可以直接赋值。

 

4、JDBC核心接口

  1、Driver

  Java.sql.Driver 接口是所有 JDBC 驱动程序需要实现的接口。这个接口是提供给数据库厂商使用的,不同数据库厂商提供不同的实现。在程序中不需要直接去访问实现了 Driver 接口的类,而是由驱动程序管理器类(java.sql.DriverManager)去调用这些Driver实现。

复制代码
package com.mysql.cj.jdbc;

import java.sql.SQLException;

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    //
    // Register ourselves with the DriverManager
    //
    static {
        try {
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }

    /**
     * Construct a new driver and register it with DriverManager
     * 
     * @throws SQLException
     *             if a database error occurs.
     */
    public Driver() throws SQLException {
        // Required for Class.forName().newInstance()
    }
}  
复制代码

  该类中static静态代码块具有将自身注册到系统中的功能。

  所谓“注册驱动”就是在调用java.sql.DriverManager.java类中的registerDriver()方法,将Driver驱动类放入ArrayList集合,然后从集合中获取驱动信息。

复制代码
public static synchronized void registerDriver(java.sql.Driver driver,
        DriverAction da)
    throws SQLException {

    /* Register the driver if it has not already been added to our list */
    if(driver != null) {
        registeredDrivers.addIfAbsent(new DriverInfo(driver, da));
    } else {
        // This is for compatibility with the original DriverManager
        throw new NullPointerException();
    }

    println("registerDriver: " + driver);

}
复制代码

 

  2、Connection

  Connection接口代表与特定的数据库的连接(会话)。在连接上下文中执行SQL语句并返回结果。

  要对数据表中的数据进行操作,首先要获取数据库连接。Connection实现就像在应用程序中与数据库之间开通了一条渠道,通过DriverManager类的getConnection()方法可获取Connection。

  

package java.sql;

import java.util.Properties;
import java.util.concurrent.Executor;

public interface Connection  extends Wrapper, AutoCloseable {
    
    Statement createStatement() throws SQLException;
    
    PreparedStatement prepareStatement(String sql)
        throws SQLException;
    
    CallableStatement prepareCall(String sql) throws SQLException;
    
    String nativeSQL(String sql) throws SQLException;
    
    void setAutoCommit(boolean autoCommit) throws SQLException;
    
    boolean getAutoCommit() throws SQLException;
    
    void commit() throws SQLException;
    
    void rollback() throws SQLException;
    
    void close() throws SQLException;
    
    boolean isClosed() throws SQLException;
    
    DatabaseMetaData getMetaData() throws SQLException;
    
    void setReadOnly(boolean readOnly) throws SQLException;
    
    boolean isReadOnly() throws SQLException;
    
    void setCatalog(String catalog) throws SQLException;
    
    String getCatalog() throws SQLException;
    
    int TRANSACTION_NONE             = 0;
    
    int TRANSACTION_READ_UNCOMMITTED = 1;
    
    int TRANSACTION_READ_COMMITTED   = 2;
    
    int TRANSACTION_REPEATABLE_READ  = 4;
    
    int TRANSACTION_SERIALIZABLE     = 8;
    
    void setTransactionIsolation(int level) throws SQLException;
    
    int getTransactionIsolation() throws SQLException;
    
    SQLWarning getWarnings() throws SQLException;
    
    void clearWarnings() throws SQLException;
    
    //--------------------------JDBC 2.0-----------------------------
    Statement createStatement(int resultSetType, int resultSetConcurrency)
        throws SQLException;
    
    PreparedStatement prepareStatement(String sql, int resultSetType,
                                       int resultSetConcurrency)
        throws SQLException;
    
    CallableStatement prepareCall(String sql, int resultSetType,
                                  int resultSetConcurrency) throws SQLException;
    
    java.util.Map<String,Class<?>> getTypeMap() throws SQLException;
    
    void setTypeMap(java.util.Map<String,Class<?>> map) throws SQLException;
    
    //--------------------------JDBC 3.0-----------------------------
    void setHoldability(int holdability) throws SQLException;
    
    int getHoldability() throws SQLException;
    
    Savepoint setSavepoint() throws SQLException;
    
    Savepoint setSavepoint(String name) throws SQLException;
    
    void rollback(Savepoint savepoint) throws SQLException;
    
    void releaseSavepoint(Savepoint savepoint) throws SQLException;
    
    Statement createStatement(int resultSetType, int resultSetConcurrency,
                              int resultSetHoldability) throws SQLException;
    
    PreparedStatement prepareStatement(String sql, int resultSetType,
                                       int resultSetConcurrency, int resultSetHoldability)
        throws SQLException;
    
    CallableStatement prepareCall(String sql, int resultSetType,
                                  int resultSetConcurrency,
                                  int resultSetHoldability) throws SQLException;
    
    PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
        throws SQLException;
    
    PreparedStatement prepareStatement(String sql, int columnIndexes[])
        throws SQLException;
    
    PreparedStatement prepareStatement(String sql, String columnNames[])
        throws SQLException;
    
    Clob createClob() throws SQLException;
    
    Blob createBlob() throws SQLException;
    
    NClob createNClob() throws SQLException;
    
    SQLXML createSQLXML() throws SQLException;
    
    boolean isValid(int timeout) throws SQLException;
    
    void setClientInfo(String name, String value)
                throws SQLClientInfoException;
    
    void setClientInfo(Properties properties)
                throws SQLClientInfoException;
    
    String getClientInfo(String name)
                throws SQLException;
    
    Properties getClientInfo()
                throws SQLException;
    
    Array createArrayOf(String typeName, Object[] elements) 
                throws SQLException;
    
    Struct createStruct(String typeName, Object[] attributes)
                throws SQLException;
    
    //--------------------------JDBC 4.1 -----------------------------
    void setSchema(String schema) throws SQLException;
    
    String getSchema() throws SQLException;
    
    void abort(Executor executor) throws SQLException;

    void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException;
    
    int getNetworkTimeout() throws SQLException;
}
    

  3、Statement

  Statement 是 Java 执行数据库操作的一个重要接口,用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句。Statement对象,用于执行不带参数的简单SQL语句。

  子接口:CallableStatement, PreparedStatement

package java.sql;

public interface Statement extends Wrapper, AutoCloseable {
    
    ResultSet executeQuery(String sql) throws SQLException;
    
    int executeUpdate(String sql) throws SQLException;
    
    void close() throws SQLException;
    
    int getMaxFieldSize() throws SQLException;
    
    void setMaxFieldSize(int max) throws SQLException;
    
    int getMaxRows() throws SQLException;
    
    void setMaxRows(int max) throws SQLException;
    
    void setEscapeProcessing(boolean enable) throws SQLException;
    
    int getQueryTimeout() throws SQLException;
    
    void setQueryTimeout(int seconds) throws SQLException;
    
    void cancel() throws SQLException;
    
    SQLWarning getWarnings() throws SQLException;
    
    void clearWarnings() throws SQLException;
    
    void setCursorName(String name) throws SQLException;
    
    //----------------------- Multiple Results --------------------------
    boolean execute(String sql) throws SQLException;
    
    ResultSet getResultSet() throws SQLException;
    
    int getUpdateCount() throws SQLException;
    
    boolean getMoreResults() throws SQLException;
    
    //--------------------------JDBC 2.0-----------------------------
    void setFetchDirection(int direction) throws SQLException;
    
    int getFetchDirection() throws SQLException;
    
    void setFetchSize(int rows) throws SQLException;
    
    int getFetchSize() throws SQLException;
    
    int getResultSetConcurrency() throws SQLException;
    
    int getResultSetType()  throws SQLException;

    void addBatch( String sql ) throws SQLException;
    
    void clearBatch() throws SQLException;
    
    int[] executeBatch() throws SQLException;
    
    Connection getConnection()  throws SQLException;
    
    //--------------------------JDBC 3.0-----------------------------
    int CLOSE_CURRENT_RESULT = 1;
    
    int KEEP_CURRENT_RESULT = 2;
    
    int CLOSE_ALL_RESULTS = 3;
    
    int SUCCESS_NO_INFO = -2;
    
    int EXECUTE_FAILED = -3;
    
    int RETURN_GENERATED_KEYS = 1;
    
    int NO_GENERATED_KEYS = 2;
    
    boolean getMoreResults(int current) throws SQLException;
    
    ResultSet getGeneratedKeys() throws SQLException;
    
    int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException;
    
    int executeUpdate(String sql, int columnIndexes[]) throws SQLException;
    
    int executeUpdate(String sql, String columnNames[]) throws SQLException;
    
    boolean execute(String sql, int autoGeneratedKeys) throws SQLException;
    
    boolean execute(String sql, int columnIndexes[]) throws SQLException;
    
    boolean execute(String sql, String columnNames[]) throws SQLException;
    
    int getResultSetHoldability() throws SQLException;
    
    boolean isClosed() throws SQLException;
    
    void setPoolable(boolean poolable)
                throws SQLException;
    
    boolean isPoolable()
                throws SQLException;
    
    //--------------------------JDBC 4.1 -----------------------------
    public void closeOnCompletion() throws SQLException;

    public boolean isCloseOnCompletion() throws SQLException;
    
    //--------------------------JDBC 4.2 -----------------------------
    default long getLargeUpdateCount() throws SQLException {
        throw new UnsupportedOperationException("getLargeUpdateCount not implemented");
    }
    
    default void setLargeMaxRows(long max) throws SQLException {
        throw new UnsupportedOperationException("setLargeMaxRows not implemented");
    }
    
    default long getLargeMaxRows() throws SQLException {
        return 0;
    }
    
    default long[] executeLargeBatch() throws SQLException {
        throw new UnsupportedOperationException("executeLargeBatch not implemented");
    }
    
    default long executeLargeUpdate(String sql) throws SQLException {
        throw new UnsupportedOperationException("executeLargeUpdate not implemented");
    }
    
    default long executeLargeUpdate(String sql, int autoGeneratedKeys)
            throws SQLException {
        throw new SQLFeatureNotSupportedException("executeLargeUpdate not implemented");
    }
    
    default long executeLargeUpdate(String sql, int columnIndexes[]) throws SQLException {
        throw new SQLFeatureNotSupportedException("executeLargeUpdate not implemented");
    }
    
    default long executeLargeUpdate(String sql, String columnNames[])
            throws SQLException {
        throw new SQLFeatureNotSupportedException("executeLargeUpdate not implemented");
    }
}

  4、ResultSet

  当使用Statement接口发送查询的SQL语句后,需要获得查询的结果返回值,ResultSet接口的功能就是封装返回值的结果,它的数据组织形式类似于二维表格,在二维表格中存储查询到的数据。

 

  以上4个接口完整地组成了使用JDBC操作数据库的基本步骤:

  首先注册Driver驱动,然后建立Connection连接,再使用Statement发送SQL语句,最后使用ResultSet接口获得查询结果。

 

  5、PreparedStatement

  PreparedStatement是预编译的,对于批量处理可以大大提高效率. 也叫JDBC存储过程。

  预编译是在执行SQL语句之前就对SQL语句进行分析、校验和优化,只执行一次预编译,后面可以多次复用预编译的对象,提升了程序运行的效率。

  在对数据库只执行一次性存取的时侯,用 Statement 对象进行处理。PreparedStatement 对象的开销比Statement大,对于一次性操作并不会带来额外的好处。

  

5、创建Driver对象

import java.sql.SQLException;

public class Test1 {
    public static void main(String[] args) throws SQLException {
        com.mysql.cj.jdbc.Driver driver = new com.mysql.cj.jdbc.Driver();
        System.out.println(driver);
    }
}

  其实在源代码中已经实现了注册驱动的过程

6、创建Connection对象

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class Test2 {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/myschool?useSSL=false&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "1234";

        Properties prop = new Properties();
        prop.setProperty("user",username);
        prop.setProperty("password",password);

        com.mysql.cj.jdbc.Driver driver = new com.mysql.cj.jdbc.Driver();
        Connection conn = driver.connect(url,prop);
        System.out.println(driver);
        System.out.println(conn);
        conn.close();
    }
}

 

7、创建Statement对象

import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class Test3 {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/myschool?useSSL=false&serverTimezone=Asia/Shanghai";

        Properties prop = new Properties();
        prop.setProperty("user","root");
        prop.setProperty("password","1234");

        Driver driver = new com.mysql.cj.jdbc.Driver();
        Connection conn = null;
        conn = driver.connect(url,prop);
        Statement stat = conn.createStatement();
        stat.executeUpdate("insert into grade(gradeName) value('教研3班')");
        stat.close();
        conn.close();
    }
}

 

8、创建ResultSet对象

import java.sql.*;
import java.util.Properties;

public class Test4 {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/myschool?useSSL=false&serverTimezone=Asia/Shanghai";

        Properties prop = new Properties();
        prop.setProperty("user","root");
        prop.setProperty("password","1234");

        Driver driver = new com.mysql.cj.jdbc.Driver();
        Connection conn = null;
        conn = driver.connect(url,prop);
        Statement stat = conn.createStatement();

        ResultSet rs = stat.executeQuery("select gradeID,gradeName from grade");
        while (rs.next()){
            int id = rs.getInt("gradeID");
            String gradeName = rs.getString("gradeName");
            System.out.println(id+""+gradeName+"");
        }
        rs.close();
        stat.close();
        conn.close();
    }
}

 

9、使用Statement接口有损程序的安全性

  实现登录功能测试:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @   盼君终得见  阅读(71)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示