如何将Java连接到Mysql?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4385392/
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 16:46:39  来源:igfitidea点击:

How to connect Java to Mysql?

javamysql

提问by karikari

I got these errors for my Java program. I have already put the mysql-connector-java-5.1.14-bin.jarinside my classpath. How to solve this?

我的 Java 程序出现了这些错误。我已经把mysql-connector-java-5.1.14-bin.jar里面的类路径。如何解决这个问题?

HSystemRDB.java:144: package com.mysql.jdbc does not exist
    Driver driver = new com.mysql.jdbc.Driver();
                                      ^
HTestClassRDB.java:99: package com.mysql.jdbc does not exist
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());

The code:

编码:

    String url = "jdbc:mysql://wire:3306/h?user="+pSystemRDB.USERNAME+"&password="+pSystemRDB.PASSWORD;
    Connection con;
    Statement stmt;
    String query1 = "Delete from dbase";
    String query2 = "Delete from id";


    try {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
    } catch (Exception e) {
        System.out.println("Class Not Found Exception:");
        System.out.println(e.getMessage());
    }

采纳答案by Wesley

You need to download the mysql package from: hereand place it inside the library, i'll edit the excact steps in a few min

您需要从以下位置下载 mysql 包:here并将其放入库中,我将在几分钟内编辑具体步骤

this is the correct syntax to connect to a database:

这是连接到数据库的正确语法:

try
{
  // create a java mysql database connection
  String myDriver = "org.gjt.mm.mysql.Driver";
  String myUrl = "jdbc:mysql://localhost/test";
  Class.forName(myDriver);
  Connection conn = DriverManager.getConnection(myUrl, "root", "");

  // your prepstatements goes here...

  conn.close();
}
catch (Exception e)
{
  System.err.println("Got an exception! ");
  System.err.println(e.getMessage());
}

Hope this helps

希望这可以帮助

回答by Jigar Joshi

You need to add MySQL Driverin your classpath for that , and import appropriate classes your source .

为此,您需要在类路径中添加MySQL 驱动程序,并导入适当的类源。

Please refer to this basic tutorial , article

请参考这个基础教程,文章

回答by Jwalant

It seems that you do not have jar file to connect database. You can download mysql-connector-java-3.1.12.jar.

您似乎没有连接数据库的 jar 文件。您可以下载mysql-connector-java-3.1.12.jar.

Please, download it and place it in the libfolder of your web application. This should fix your problem.

请下载它并将其放在lib您的 Web 应用程序的文件夹中。这应该可以解决您的问题。

If you have any other problem, you can refer this tutorial for steps to connect MySQL using JDBC

如果您有任何其他问题,您可以参考本教程了解使用 JDBC 连接 MySQL 的步骤