我想在 Kotlin 代码中使用
java.sql.DriverManager
连接 MySQL 数据库。
这是有关 MySQL 中连接的信息。
GCP
dev
0000
3306
这是我用 Kotlin 编写的简单代码。
package org.example;
import java.sql.DriverManager;
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) {
try{
var availableDrivers = DriverManager.getDrivers();
System.out.println("Drivers available");
while(availableDrivers.hasMoreElements()){
var driver = availableDrivers.nextElement();
System.out.println(driver);
}
System.out.println("end of Drivers available");
} catch (Exception e) {
System.out.println(e.getMessage());
}
//var url = "jdbc:mysql://localhost:3306/TestConnection1";
//var user = "root";
//var password = "MySQLJay30";
var url = "jdbc:mysql://35.194.200.2:3306/GCP";
var user = "dev";
var password = "0000";
try{
System.out.println("Connecting to database...");
var connection = DriverManager.getConnection(url, user, password);
System.out.println("Connected");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
在IntelliJ中,控制台的输出如下。
11:16:47 AM: Executing ':org.example.Main.main()'...
> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes
> Task :org.example.Main.main()
Drivers available
end of Drivers available
Connecting to database...
No suitable driver found for jdbc:mysql://35.194.200.2:3306/GCP
BUILD SUCCESSFUL in 581ms
2 actionable tasks: 2 executed
11:16:48 AM: Execution finished ':org.example.Main.main()'.
我还检查了我是否添加了从
Maven下载的
mysql-connector-j-9.0.0.jar
我昨天查看了 JDBC powerpoint 和 java.sql.DriverManager API (Java SE 11)。
最初由 seenukarthi 作为评论发布:
添加
作为 gradle 依赖项,不在 IntelliJ 库。mysql-connector-j-9.0.0
implementation group: 'com.mysql', name: 'mysql-connector-j', version: '9.0.0'