How to determine or switch the current database using the Teradata JDBC Driver

Blog
The best minds from Teradata, our partners, and customers blog about whatever takes their fancy.
Teradata Employee

Question

We can establish a JDBC Connection with URL that specifies a database name, e.g.

jdbc:teradata://<some host>/DATABASE=<some database>

After the Connection is opened, is there any way to determine what database is in use? And is there any way to switch to a different database?

Answer

The Teradata Database concept of a "database" corresponds to the JDBC API concept of a "schema". Ideally, the JDBC API would offer Connection methods getSchema and setSchema to do these operations in a standard way, but there are no such methods.

The Teradata Database's "help session" command returns the session's current database, so your own getSchema method can be implemented as follows.

public static String getSchema (Connection con)
throws SQLException
{
 Statement stmt = con.createStatement () ;
 try {
  ResultSet rs = stmt.executeQuery ("help session") ;
  try {
   rs.next () ;
   return rs.getString (5) ;
  } finally { rs.close () ; }
 } finally { stmt.close () ; }
}

The Teradata Database's "database" command switches the session's current database, so your own setSchema method can be implemented as follows.

public static void setSchema (Connection con, String sName)
throws SQLException
{
 Statement stmt = con.createStatement () ;
 try {
  stmt.executeUpdate ("database " + sName) ;
 } finally { stmt.close () ; }
}