2013-12-11 148 views
0

当我尝试编译无法连接到我的数据库

ConnectDB.java:14: error: unreported exception ClassNotFoundException; must be caught or declared to be thrown 
Class.forName("com.mysql.jdbc.Driver"); 

import java.sql.*; 
import java.sql.Connection; 
import java.sql.DriverManager; 

public class ConnectDB 
{ 
    public ConnectDB() throws SQLException 
    { 
     Class.forName("com.mysql.jdbc.Driver"); 
     Connection dbConnect = DriverManager.getConnection("jdbc:mysql://xx.xx.xxx.xxx:3306/my_DB", "userName", "superSecurePassword"); 
    } 
} 

我已经下载并安装驱动程序,并设置类路径,但继续得到错误,我得到这个错误。

回答

4

这是因为编译器告诉你,你没有捕获检查的异常。您需要适当的处理:

try { 
    Class.forName("com.mysql.jdbc.Driver"); 
} catch(ClassNotFoundException e) { 
    // log exception, probably abort application if it can't run without a database 
} 
1

您需要将下面的代码

Class.forName("com.mysql.jdbc.Driver") 

一个try catch块内。因为代码抛出 * 检查异常 *和编译器强制为catch检查异常