Collection Contents Index JDBC overview Using JDBC to access data pdf/chap18.pdf

User's Guide
   PART 3. Java in the Database
     CHAPTER 18. Data Access Using JDBC       

Establishing JDBC connections


This section presents classes that establish a JDBC database connection from a Java application.

Top of page  Connecting from a JDBC client application

If you wish to access database system tables (database metadata) from a JDBC application, you must add a set of jConnect system objects to your database. If you do not need to access the system tables, you do not need to add these objects.

For Info     For information about adding the jConnect system objects to a database, see Using the Sybase jConnect JDBC driver.

The following complete Java application is a command-line application that connects to a running database, prints a set of information to your command line, and terminates.

Establishing a connection is the first step any JDBC application must take when working with database data.

For Info     This example illustrates an external connection, which is a regular client/server connection. For information on how to create an internal connection, from Java classes running inside the database server, see Establishing a connection from a server-side JDBC class.

Top of page  External connection example code

The following is the source code for the methods used to make a connection. The source code can be found in the main method and the ASAConnect method of the file JDBCExamples.java in the jxmp directory under your Adaptive Server Anywhere installation directory:

// Import the necessary classes
import java.sql.*;             // JDBC
import com.sybase.jdbc.*;      // Sybase jConnect
import java.util.Properties;   // Properties
import sybase.sql.*;           // Sybase utilities
import asademo.*;              // Example classes

private static Connection conn;
public static void main(String args[])  {

    conn = null;
    String machineName;
    if ( args.length != 1 ) {
      machineName = "localhost";
    } else {
      machineName = new String( args[0] );
    }

    ASAConnect( "dba", "sql", machineName );
    if( conn!=null ) {
        System.out.println( "Connection successful" );
    }else{
        System.out.println( "Connection failed" );
    }

    try{
      serializeVariable();
      serializeColumn();   
      serializeColumnCastClass();
    }
    catch( Exception e ) {
      System.out.println( "Error: " + e.getMessage() );
      e.printStackTrace();
    }  
  }
}
private static void ASAConnect( String UserID, 
                              String Password, 
                              String Machinename ) {
    // uses global Connection variable
    
    String _coninfo = new String( Machinename );
    
    Properties _props = new Properties();
    _props.put("user", UserID );
    _props.put("password", Password );
    
    // Load the Sybase Driver
    try {
      Class.forName("com.sybase.jdbc.SybDriver").newInstance();
      
      StringBuffer temp = new StringBuffer();
      // Use the Sybase jConnect driver...
      temp.append("jdbc:sybase:Tds:"); 
      // to connect to the supplied machine name...
      temp.append(_coninfo);
      // on the default port number for ASA...
      temp.append(":2638");
      // and connect.
      System.out.println(temp.toString());
      conn = DriverManager.getConnection( temp.toString() , _props );
    }
    catch ( Exception e ) {
      System.out.println("Error: " + e.getMessage());
      e.printStackTrace();
    }   
  }

Top of page  How the external connection example works

The external connection example is a Java command-line application.

Importing packages 

The application requires several libraries, which are imported in the first lines of JDBCExamples.java:

The main method 

Each Java application requires a class with a method named main, which is the method invoked when the program is started. In this simple example, JDBCExamples.main is the only method in the application.

The JDBCExamples.main method carries out the following tasks:

  1. Processes the command-line argument. If a machine name is supplied, then this is used. By default, the machine name is set to localhost, which is appropriate for the personal database server.

  2. Calls the ASAConnect method to establish a connection.

  3. Executes several methods that scroll data to your command line.

The ASAConnect method 

The JDBCExamples.ASAConnet method carries out the following tasks:

  1. Connects to the default running database using Sybase jConnect.

  2. Returns control to the calling method.

Top of page  Running the external connection example

This section describes how to run the external connection example

  To create and execute the external connection example application:
  1. From a system command prompt, change to the Adaptive Server Anywhere installation directory. Then change to the jxmp subdirectory

  2. Ensure that your CLASSPATH environment variable is set to include the current directory (.) and the zip files that are imported. For example, from a command prompt (the following should be entered all on one line):

    set classpath=..\java\jdbcdrv.zip;.;..\java\asajdbc.zip;asademo.jar

    The default zip file name for Java is classes.zip. For classes in any file named classes.zip, you only need the directory name in the CLASSPATH variable, not the zip-file name itself. For classes in files with other names, you must supply the zip file name.

    You need the current directory in the CLASSPATH in order to run the example.

  3. Ensure that the database is loaded onto a database server running TCP/IP. You can start such as server on your local machine using the following command (from the jxmp subdirectory):

    start dbeng6 -c 8M  ..\asademo
  4. Run the example by entering the following at the command prompt:

    java JDBCExamples

    If you wish to try this against a server running on another machine, you must enter the correct name of that machine. The default is localhost, which is as an alias for the current machine name.

  5. Confirm that a list of people and products is displayed at your command prompt.

    If the attempt to connect fails, an error message is displayed instead. Confirm that you have executed all the steps as required. The most common mistake is to have an incorrect CLASSPATH, which results in a failure to locate a class.

For Info     For more information about using jConnect, see Using the Sybase jConnect JDBC driver and the online documentation for jConnect.

Top of page  Establishing a connection from a server-side JDBC class

SQL statements in JDBC are built using the createStatement method of a Connection object. Even classes running inside the server need to establish a connection in order to create a Connection object.

Establishing a connection from a server-side JDBC class is more straightforward than establishing an external connection. Because the server-side class is executed by a user already connected, the class simply uses the current connection.

Top of page  Server-side connection example code

The following is the source code for the example. The source code can be found in the InternalConnect method of JDBCExamples.java in the jxmp directory under your Adaptive Server Anywhere installation directory:

public static void InternalConnect() {
  try {
      conn = DriverManager.getConnection("jdbc:default:connection");
      System.out.println("Hello World");
    }
    catch ( Exception e ) {
      System.out.println("Error: " + e.getMessage());
      e.printStackTrace();
    }
  }
}

Top of page  How the server-side connection example works

In this simple example, InternalConnect() is the only method used in the application.

The application requires only one of the libraries (JDBC) imported in the first line of the JDBCExamples.java class. The others are required for external connections. The JDBC classes are contained in the package named java.sql.

The InternalConnect() method carries out the following tasks:

  1. Connects to the default running database using the current connection:

  2. Prints Hello World to the current standard output, which is the server window. System.out.println carries out the printing.

  3. If there is an error in the attempt to connect, an error message is printed to the server window, together with the place where the error occurred.

    The try and catch instructions provide the framework for the error handling.

  4. The class terminates.

Top of page  Running the server-side connection example

This section describes how to run the server-side connection example.

  To create and execute the internal connection example application:
  1. If you have not already done so, compile the JDBCExamples.java file. If you are using the JDK, you can do the following in the jxmp directory from a command prompt:

    javac JDBCExamples.java
  2. Start a database server using the sample database. You can start such as server on your local machine using the following command (from the jxmp subdirectory):

    start dbeng -c 8M ..\asademo

    The TCP/IP network protocol is not required in this case, as jConnect is not being used. However, you must have at least 8 Mb of cache available to use Java classes in the database.

  3. Install the class into the sample database. Once connected to the sample database, you can do this from Interactive SQL using the following command:

    INSTALL JAVA NEW 
    FROM FILE 'path\jxmp\JDBCExamples.class'

    where path is the path to your installation directory.

    You can also install the class using Sybase Central. While connected to the sample database, open the Java Objects folder and double click Add Class. Then follow the instructions in the wizard.

  4. You can now call the InternalConnect method of this class just as you would an stored procedure:

    CALL JDBCExamples>>InternalConnect()

    The first time a Java class is called in a session, the internal Java virtual machine must be loaded. This can take a few seconds.

  5. Confirm that the message Hello World is printed on the server screen.

Top of page  Notes on JDBC connections

Top of page  

Collection Contents Index JDBC overview Using JDBC to access data pdf/chap18.pdf