简体   繁体   English

使用Java连接到MySQL数据库

[英]Connecting to a mySQL database using Java

So I just started learning about databases this week and one of the things I need to be able to do is connect to my mySQL database that I created using Java. 因此,本周我才开始学习数据库,我需要做的一件事情就是连接到使用Java创建的mySQL数据库。 I have done some research and I have tried to find the correct way of doing this I just can't seem to figure out how. 我做了一些研究,我试图找到正确的方法来做,但我似乎还不知道怎么做。 Here is my code: 这是我的代码:

 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.SQLException;
 public class Menu
 {
public void menu()
{
    Connection conn;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "gym";
    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 =(");
        System.out.println(e.getMessage());
    }
  }

}

Now the problem is, is that every time I run this code, the "No Connection =( " appears and then it says the error is: "com.mysql.jdbc.Driver". Can somebody please help me and say what I am doing wrong? Thank you. Much appreciated. 现在的问题是,每次我运行此代码时,都会出现“ No Connection =(”,然后提示错误是:“ com.mysql.jdbc.Driver”。有人可以帮助我并说我是什么吗?做错了吗?谢谢,非常感谢。

Your error means that your library path doesn't contain the jar that contains the com.mysql.jdbc.Driver class. 您的错误意味着您的库路径不包含包含com.mysql.jdbc.Driver类的jar。

You don't have to change anything in your code. 您无需更改代码中的任何内容。 If you are running it via Eclipse, you should add mysql-connector-java-xxx-bin.jar to your build path (where xxx is the version of the jar). 如果通过Eclipse运行,则应将mysql-connector-java-xxx-bin.jar到构建路径(其中xxx是jar的版本)。

All JDBC connection classes need their respective drivers which are normally supplied as jar files from the database vendor, add the relevant database driver to your classpath. 所有JDBC连接类都需要它们各自的驱动程序,这些驱动程序通常由数据库供应商以jar文件的形式提供,并将相关的数据库驱动程序添加到您的类路径中。

The .jar file will be available from the vendors site, in this case : http://www.mysql.com/products/connector/ and then to add this to the classpath of your project in the ide of your choice. .jar文件可从供应商站点获得,在这种情况下,该站点为: http : //www.mysql.com/products/connector/ ,然后根据需要将其添加到项目的类路径中。 Here is a guide for eclipse : http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java) 这是蚀的指南: http : //www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)

Try and run again once you have this. 遇到这个问题后,请尝试并再次运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM