我是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
任何人都可以告诉我它为什么会发生吗?!
答案 0 :(得分: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();
}
注意:通常如果(con == null)永远不会执行,因为driver.connect()会抛出异常