mysql-connector-java本地试验
题外话:因为Intellij配置报错java: 错误: 不支持发行版本 5
,试过调整project structure也不行,所以直接在Ubuntu里搞
- 环境:Ubuntu 22.04
- 软件:MySQL 8.0.39, jdk17.0.12
编写数据库
CREATE DATABASE test_db;
USE test_db;
CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
age INT
)
INSERT INTO users (name, age) VALUES ('Alice', 25), ('Bob', 30);
EXIT;
创建项目文件
mkdir ~/my-java-project && cd ~/my-java-project
vim编写Main.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main{
public static void main(String[] args){
String jdbcUrl = "jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=UTC";
String username = "root";
String password = "密码"; //替换成MySQL密码
Connection connection = null;
Statement statement = null;
try{
connection = DriverManager.getConnection(jdbcUrl, username, password);
statement = connection.createStatement();
String sql = "SELECT * FROM users";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("ID:" + resultSet.getInt("id"));
System.out.println("Name:" + resultSet.getString("name"));
System.out.println("Age:" + resultSet.getInt("age"));
}
resultSet.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(statement != null) statement.close();
if(connection !=null) connection.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
ESC :wq退出编辑
trouble shooting
- 官网下载MySQL对应驱动包
- 移动包到项目文件夹
- 这里官网下载的为".deb"包,需要安装,安装完成后所在目录一般为/usr/share/java/mysql-connector-java-x.x.x.jar,
- 没有对应的版本,所以我下载了9.0.0
cp /mnt/c/Users/用户名/Downloads/mysql-connector-j-9.0.0-1ubuntu22.04_all.deb ~/my-java-project/ //移动到项目文件夹
dpkg -i mysql-connector-j_9.0.0-1ubuntu22.04_all.deb //这里名字容易打错,注意下划线
- 编译与执行
javac -cp .:/usr/share/java/mysql-connector-java-x.x.x.jar Main.java
java -cp .:/usr/share/java/mysql-connector-java-x.x.x.jar Main
- 输出
ID:1
Name:Alice
Age:25
ID:2
Name:Bob
Age:30
- MySQL用户权限(若出现拒绝访问)
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
EXIT;
参数解释
dbkg: 包管
|: 管操符
grep: 搜文,后接字段名
-f: apt-get选项,fix-broken,修复依赖关系
-cp: 指定路径,'.'指当前路径,':/usr/share/'指jar文件路径,这样做将类文件和jar加入jvm类路径。