0

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?!

2
  • 1
    Let us see the error stacktrace use sqlex.printStackTrace(); Commented Jul 6, 2013 at 15:25
  • ok, here you are:) : Exception in thread "main" java.lang.NullPointerException at Test1.main(Test1.java:38) Commented Jul 6, 2013 at 15:26

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

oh may bad! yes, you're right. I grabed this code from a book and just trusted the code. I erased that line and now connection is ok! thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.