Friday, April 25, 2014

Does this Connection object have no schema?


This is the output of the program given below:



Java Code:



Connection made!
Schema Name:null

Successfully connected to null
Releasing all open resources ...

Inside establishConnection(), conn is initialized as null. Then the first statement inside the try block is supposed to establish a connection with the database, and the third statement is then printing the name of the current schema of conn.

According to the API, getSchema() returns the current schema name or null if there is none.


This means that there is no schema (I think the schema name is same as the database name) associated with conn? Can anyone suggest if I am correct in my anticipation, and also suggest why is that there is no schema or null associated with conn?



Java Code:



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectDB {

private Connection establishConnection() throws SQLException {
Connection conn = null;
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test_final1", "root", "password");
System.out.println("Connection made!\n");
System.out.println("Schema Name:"+conn.getSchema());
} catch (SQLException sqle) {
System.err.println("SQL Exception thrown while making connection");
printSQLException(sqle);
}
return conn;
}

public static void main(String[] args) {
ConnectDB cdb= new ConnectDB();
Connection myconn=null;;
try{
myconn=cdb.establishConnection();
if(myconn!=null) System.out.println("Successfully connected to " + myconn.getSchema());
}catch (SQLException e) {
ConnectDB.printSQLException(e);
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
ConnectDB.closeConnection(myconn);
}

}


public static void printSQLException(SQLException ex) {
for (Throwable e : ex) {
if (e instanceof SQLException) {
if (ignoreSQLException(((SQLException)e).getSQLState()) == false) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException)e).getSQLState());
System.err.println("Error Code: " + ((SQLException)e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}



public static boolean ignoreSQLException(String sqlState) {
if (sqlState == null) {
System.out.println("The SQL state is not defined!");
return false;
}
// X0Y32: Jar file already exists in schema
if (sqlState.equalsIgnoreCase("X0Y32"))
return true;
// 42Y55: Table already exists in schema
if (sqlState.equalsIgnoreCase("42Y55"))
return true;
return false;
}


public static void closeConnection(Connection connArg) {
System.out.println("Releasing all open resources ...");
try {
if (connArg != null) {
connArg.close();
connArg = null;
}
} catch (SQLException sqle) {
printSQLException(sqle);
}
}

}


No comments:

Post a Comment