2013-11-28 236 views
0

我正在尝试编写一个Java程序,为了工作,需要访问MySQL数据库。以下是目前为止该计划的代码,与I.P.地址,用户名和密码因安全原因被删除。此代码的问题在于,无论何时运行,它总是无法连接到服务器,即使我知道它正在运行并且登录信息的密码正确。我的朋友在网上发现了一个程序,检查你的数据库是否可以连接,并且每当他运行它时,它总是输出“你的MySQL JDBC驱动程序在哪里?”什么是MySQL JDBC驱动程序?我认为这是我的问题的原因,但我确实不知道。任何人都可以向我解释这个吗?Java无法连接到MySQL服务器

import java.sql.*; 

public class main 
{ 
    public static void main(String[] args) 
    { 
     // Store the information to connect to the MySQL server in handy variables. 
     String url = "jdbc:mysql://(IP REMOVED FOR SAFETY):3307/"; 
     String dbName = "attendance"; 
     String driver = "com.mysql.jdbc.Driver"; 
     String userName = "(USERNAME REMOVED FOR SAFETY)"; 
     String password = "(PASSWORD REMOVED FOR SAFETY)"; 


     // Now let's connect! 
     try { 
      Class.forName(driver).newInstance(); 
      Connection conn = DriverManager.getConnection(url+dbName,userName,password); 
     } catch (Exception e) { 
      System.out.println("Could not connect to database!"); 
     } 
    } 
} 
+0

司机是这似乎是从你的classpath – JamesB

+0

缺失,这可能是有益的[例子链接](HTTP类com.mysql.jdbc.Driver:// www.roseindia.net/tutorial/java/jdbc/jdbcdrivermanager.html) –

+0

@robert lennon没有来自roseindia.net的链接是有帮助的。 – JamesB

回答

0

MySQL JDBC驱动程序被称为MySQL连接/ J。这个jar需要被添加到你的程序运行的类路径中。

驱动程序可以下载来自:http://dev.mysql.com/downloads/connector/j/

+0

感谢您的支持,但通过我自己的无知,我不知道如何将jar添加到类路径中。我正在研究它,但如果有人向我解释过程,我将不胜感激。 – DavidB

+0

@DavidB你目前如何运行你的代码? – JamesB

+0

在[BlueJ](http://www.bluej.org/)内。 – DavidB