This section describes how to select a database on the SQL Server to be the current database.
When you connect to a SQL Server, it will set the default database associated to the login name
as the current database. You can set the current database to be a different database by including
another property, database=name, in the connect URL string.
Here is my sample program that connects to my SQL Server through the JDBC-ODBC Bridge and sets
the current database to "AdventureWorksLT":
/**
* OdbcSqlServerCurrentDatabase.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class OdbcSqlServerCurrentDatabase {
public static void main(String [] args) {
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(
"jdbc:odbc:SQL_SERVER;user=sa;password=HerongYang;"
+"database=AdventureWorksLT");
// Checking the database name
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery("SELECT DB_NAME()");
res.next();
String name = res.getString(1);
System.out.println("Current database: "+name);
con.close();
} catch (Exception e) {
System.err.println("Exception: "+e.getMessage());
}
}
}
The output confirms that the "database=name" property in the connection URL worked ok: