为什么我无法在 Kotlin 中连接 java.sql.DriveManager?

问题描述 投票:0回答:1

我想在 Kotlin 代码中使用

java.sql.DriverManager
连接 MySQL 数据库。

这是有关 MySQL 中连接的信息。

  • 连接名称:
    GCP
  • 用户名:
    dev
  • 密码:
    0000
  • 港口:
    3306

My info about connection in MySQL

这是我用 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

MySQL-connector-J jar

我昨天查看了 JDBC powerpoint 和 java.sql.DriverManager API (Java SE 11)

检查语法 Syntax to get Connection instance in Java code

kotlin gradle jdbc
1个回答
0
投票

最初由 seenukarthi 作为评论发布:

添加

mysql-connector-j-9.0.0
作为 gradle 依赖项,不在 IntelliJ 库。
implementation group: 'com.mysql', name: 'mysql-connector-j', version: '9.0.0'

© www.soinside.com 2019 - 2024. All rights reserved.