我是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
谁能告诉我为什么会这样?!
最佳答案
您自己在这一行中抛出异常:
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() 会抛出异常
关于通过 JDBC 连接到数据库时出现 java SQLException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17504320/