數據庫連接
1. 在web.xml中配置(不要介意版本號是否對應mysql的版本 我的mysql版本為 5.7.34 沒有對應的jar 包,但是依舊可以使用)
```xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
<scope>runtime</scope>
</dependency>
```
2. 然后是連接數據庫
步驟如下:
3. 測試連接
import java.sql.*;
public class Test {
public static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
//8.0以上版本的數據庫,驅動器是com.mysql.cj.jdbc.Driver,而不是之前的com.mysql.jdbc.Driver
public static final String DB_URL = "jdbc:mysql://localhost:3306/jdbc?serverTimezone" +
"=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false";
//8.0以上版本的數據庫要在后面加上 ?useSSL=false&serverTimezone=UTC
//在這個語句中,localhost是數據庫鏈接名稱,3306是端口號,jdbc是要訪問的數據庫
public static final String USER = "root";//數據庫用戶名
public static final String PASS = "123456";//數據庫密碼
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//注冊jdbc驅動
Class.forName(JDBC_DRIVER);
//打開鏈接
System.out.println("連接數據庫...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("連接成功");
//執行查詢
System.out.println("實例化Statement...");
stmt = conn.createStatement();
String sql;
System.out.println("開始查詢數據庫");
sql = "select * from jdbc.users";//查詢jdbc數據表,此處可能爆紅,不要介意直接運行。如果介意,設置的搜索框內輸入:SQL Dialects
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String pwd = rs.getString("pwd");
System.out.print("ID:" + id);
System.out.print(" name:" + name);
System.out.print(" password:" + pwd);
System.out.println();
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}