0

我是 java 新手,正在尝试创建一个数据库并使用这个简单的程序访问它:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.derby.jdbc.EmbeddedDriver;


public class Test1 {

    public static void main(String[] args) {
    final String url = "jdbc:derby:emp"; 
    Driver driver=new EmbeddedDriver();
    Properties prop=new Properties();
    prop.put("create", "true");

    try (Connection con = driver.connect(url, prop)) 
    { 
    // Perform useful work. The following throw statement simulates a 
    // JDBC method throwing SQLException. 
    throw new SQLException("Unable to access database table", 
    new java.io.IOException("File I/O problem")); 
    } 
    catch (SQLException sqlex) 
    { 
    while (sqlex != null) 
    { 
    System.err.println("SQL error : "+sqlex.getMessage()); 
    System.err.println("SQL state : "+sqlex.getSQLState()); 
    System.err.println("Error code: "+sqlex.getErrorCode()); 
    System.err.println("Cause: "+sqlex.getCause()); 
    sqlex = sqlex.getNextException(); 
    } 
    }
}
}

我已将所需的库放入我的类路径并在运行配置中设置 DERBY_HOME 变量。我看到确实创建了数据库文件,但是运行时出现以下错误,并且无法访问数据库:

SQL error : Unable to access database table
SQL state : null
Error code: 0
Cause: java.io.IOException: File I/O problem

谁能告诉我为什么会这样?!

4

1 回答 1

5

您在这一行中自己抛出异常:

throw new SQLException("Unable to access database table", 
    new java.io.IOException("File I/O problem")); 

这应该是有条件的:

Connection con=null;
try {
    con=driver.connect(url, prop);
    if (con==null) {
    throw new SQLException("Unable to access database table", 
        new java.io.IOException("File I/O problem")); 
} catch (Throwable t) {
    t.printStackTrace();
} finally {
 //close every thing not is null
 if (con!=null) con.close();
} 

注意:通常 if (con==null) 永远不会执行,因为 driver.connect() 会抛出异常

于 2013-07-06T15:32:30.333 回答