【一】JDBC核心技术
1、什么是JDBC
Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。我们通常说的JDBC是面向关系型数据库的。——百度百科
JDBC的主要作用并不只是连接数据库,更加强大的功能在于,只要数据库支持SQL语句,就可以使用JDBC技术在Java语言中执行SQL语句,从而达到与数据库进行通信的目的。
JDBC还可以获取数据库、数据表及其数据库对象的基本信息,但其最常使用的功能还是对数据库进行增删改查操作。
2、为什么要使用JDBC
首先我们来了解下数据库概念:
简单地说,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接口有损程序的安全性
实现登录功能测试:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南