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

Specifying Port Number in Connection URL

This section describes how to specify port numbers in the connection URL.

If the SQL Server is configured with a non-default port number, you need to specify the port number in the connection url in the following syntax:

jdbc:sqlserver://server_name:port;user=login;password=****

For example, if you installed the SQL Server 2005 Express Edition, it will be configured with 1269 as the port number.

The tutorial program below shows you how to include port number 1296 in the connection url:

/**
 * ConnectionTest3.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.sql.*;
public class ConnectionTest3 {
  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");

// Connection is ready to use
      DatabaseMetaData meta = con.getMetaData();
      System.out.println("Driver name: "
        + meta.getDriverName());
      System.out.println("Driver version: "
        + meta.getDriverVersion());
      System.out.println("Server name: " 
        + meta.getDatabaseProductName());
      System.out.println("Server version: "
        + meta.getDatabaseProductVersion());
      System.out.println("Connection URL: "
        + meta.getURL());
      System.out.println("Login name: "
        + meta.getUserName());

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

Compile and run it, you should get:

C:\>\progra~1\java\jdk1.6.0_02\bin\javac ConnectionTest3.java

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

Driver name: Microsoft SQL Server 2005 JDBC Driver
Driver version: 1.0.809.102
Server name: Microsoft SQL Server
Server version: 9.00.1399
Connection URL: jdbc:sqljdbc://
Login name: sa

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 Port Number in Connection URL