如何在 JAVA 中建立 MySQL 连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4172692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:18:40  来源:igfitidea点击:

How to make a MySQL Connection in JAVA

javamysqlnetbeansjdbc

提问by Sandeep Bansal

I can't seem to get a connection made on my Java program to java, I have started the MySQL Server, made a database in phpMyAdmin. But I'm confused on how I should use the JDBC Driver that I downloaded from MySQL.

我似乎无法在我的 Java 程序上建立到 java 的连接,我已经启动了 MySQL 服务器,在 phpMyAdmin 中建立了一个数据库。但是我对如何使用从 MySQL 下载的 JDBC 驱动程序感到困惑。

Here's my code:

这是我的代码:

    private void startConnection()
{
Connection conn = null;
String url = "jdbc:mysql://localhost/";
String dbName = "bank";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
} catch (Exception e) {
    System.out.println("NO CONNECTION =(");
}
}

I had included the jar file in my JDK - jre\lib\ext folder but nothing. Any ideas?

我已经将 jar 文件包含在我的 JDK - jre\lib\ext 文件夹中,但什么也没有。有任何想法吗?

Thanks in advance.

提前致谢。

采纳答案by corriganjc

One thing stands out: you haven't specified a network port in the URL. The default port is 3306. So try:

有一点很突出:您没有在 URL 中指定网络端口。默认端口是 3306。所以尝试:

jdbc:mysql://localhost:3306/

For the URL.

对于网址。

回答by Alexis Dufrenoy

You have to specify the port. It's String url = "jdbc:mysql://localhost:3306/";by default.

您必须指定端口。这是String url = "jdbc:mysql://localhost:3306/";默认的。

回答by CodeMadness

private void startConnection()
{
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "bank";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "password";

    try
    {
        Class.forName(driver).newInstance();
        conn = DriverManager.getConnection(url+dbName,userName,password);
        System.out.println("Connected to the database");
        conn.close();
        System.out.println("Disconnected from database");

    }
    catch (Exception e)
    {
        System.out.println("NO CONNECTION =(");
    }
}

This will work

这将工作