简体   繁体   中英

java SQLException when connecting to DB via JDBC

I'm new to java and am trying to create a database and access it with this simple program:

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(); 
    } 
    }
}
}

I've put the required libraries into my classpath and set the DERBY_HOME variable in run configuration. I see that database files are actually created, but I get the following error when running it, and I can't access the database:

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

can anyone tell me why it's happening?!

You are throwing the exception yourself in this line:

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

This should be conditional:

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();
} 

NOTE: Usually if (con==null) will never execute because driver.connect() will throw an exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM