本文最后更新于605 天前,其中的信息可能已经过时,如有错误请发送邮件到2192492965@qq.com
JDBC引入与使用
Java数据库连接(JDBC)是一个Java API,它定义了客户端如何连接和执行数据库操作。使用JDBC,开发者可以通过标准的SQL语句与各种数据库进行交互。本文将介绍如何在Maven项目中引入JDBC以及如何使用它来执行数据库操作。
为什么使用JDBC?
JDBC提供了一种统一的数据库访问方法,使得开发者无需关心底层数据库的具体实现。通过JDBC,开发者可以使用简单的SQL语句来查询、更新和管理数据,同时JDBC还支持连接池、事务控制等高级特性。在Maven项目中引入JDBC
要在Maven项目中使用JDBC,首先需要在项目的pom.xml文件中添加JDBC驱动的依赖。以MySQL为例,以下是添加MySQL JDBC驱动依赖的代码:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
*注意:jdbc依赖版本需和本机mysql版本对应
使用JDBC执行数据库操作
编写数据库连接工具类
package org.example.www.exp02.utils;
import java.sql.*;
public class DB {
static String username = "root";
static String password = "123456";
static String database = "book";
static String url = "jdbc:mysql://localhost:3306/"+database+"?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
static String drive = "com.mysql.cj.jdbc.Driver";
static {
try {
Class.forName(drive);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(url,username,password);
if(connection!=null) {
System.out.println(connection);
return connection;
}else {
System.out.println("数据库连接失败");
return null;
}
}
public static void closeAll(Connection connection, ResultSet result, PreparedStatement statement) throws SQLException{
closeconnection(connection);
closestatement(statement);
closeresult(result);
}
public static void closestatement(PreparedStatement statement) throws SQLException{
statement.close();
}
public static void closeconnection(Connection connection) throws SQLException{
connection.close();
}
public static void closeresult(ResultSet result)throws SQLException {
result.close();
}
}




