关于java连接mysql8需要注意的事

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.sql.*;

public class Main {
public static void main(String[] args) throws SQLException {
//// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
// static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
// static final String DB_URL = "jdbc:mysql://[ip]:[port]/[库]";

// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
final String DB_URL = "jdbc:mysql://[ip]:[port]/[库]?serverTimezone=GMT&characterEncoding=UTF-8&useSSL=false";

//java项目www.fhadmin.org
// 数据库的用户名与密码,需要根据自己的设置
final String USER = "user";
final String PASS = "password";
try {
Class.forName(JDBC_DRIVER);
System.out.println("驱动加载成功!");
// Log.d("TAG", "linkMysql: qudong");
// Log.d("TAG", DriverManager.getConnection(url, user, pwd).toString());
}
catch (Exception e){
// Log.d("TAG", "linkMysql: 失败1");
e.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("连接数据库成功!");
// Log.d("TAG", "linkMysql: 连接数据库成功");
}
catch (Exception e){
// Log.d("TAG", "linkMysql: 失败2");
e.printStackTrace();
}

Connection conn = null;
Statement stmt = null;
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);

// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
conn.setAutoCommit(true);
System.out.println("连接数据库成功");
stmt = conn.createStatement();
String sql;
sql = "drop table hehe";
int i=stmt.executeUpdate(sql);
if (i > 0) {
System.out.println("删除成功");
}

// 执行查询
// System.out.println(" 实例化Statement对象...");
// stmt = conn.createStatement();
// String sql;
// sql = "SELECT id, name, url FROM websites";
// ResultSet rs = stmt.executeQuery(sql);

// 展开结果集数据库
// while(rs.next()){
// // 通过字段检索
// int id = rs.getInt("id");
// String name = rs.getString("name");
// String url = rs.getString("url");
//
// // 输出数据
// System.out.print("ID: " + id);
// System.out.print(", 站点名称: " + name);
// System.out.print(", 站点 URL: " + url);
// 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!");
}
}