JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

Specifying Database Name in Connection URL

This section describes how to specify database name in connection URL.

When you create a connection object to a SQL Server without specifying any database name, the SQL Server will connect you to the default database that is linked to the login name. For example, "master" is the default database for login name "sa". If you create a connection with "sa" login name, the connection will be linked to "master" database.

If you want to work with a different database, you must specify the database name in the connection url in the following syntax:

jdbc:sqlserver://server_name:port;database=name;...

The tutorial program below shows you how to connect to the local SQL Server and select the sample database "AdventureWorksLT" as the working database.

/**
 * SelectDatabase.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.sql.*;
public class SelectDatabase {
  public static void main(String [] args) {
    Connection con = null;
    try {

// Load Microsoft JDBC Driver 1.0
      Class.forName(
        "com.microsoft.sqlserver.jdbc.SQLServerDriver");

// Obtaining a connection to SQL Server
      con = DriverManager.getConnection(
          "jdbc:sqlserver://localhost:1269;"
        + "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("Connected to database: "+name);

      con.close();        
    } catch (java.lang.ClassNotFoundException e) {
      System.err.println("ClassNotFoundException: "
        +e.getMessage());
    } catch (SQLException e) {
      System.err.println("SQLException: "
        +e.getMessage());
    }
  }
}

The program output will confirm you that the database is selected correctly.

C:\>\progra~1\java\jdk1.6.0_02\bin\java -cp .;\local\lib\sqljdbc.jar
   SelectDatabase

Connected to database: AdventureWorksLT

Sections in This Chapter

Installing Microsoft JDBC Driver for SQL Server

Loading Driver Class with Class.forName()

DriverManager.getConnection() and Connection URL

Specifying Port Number in Connection URL

Closing the Database Connection - con.close()

Specifying Database Name in Connection URL

Incorrect Database Name in Connection URL

Creating Connections with DataSource Class

Dr. Herong Yang, updated in 2007
Specifying Database Name in Connection URL