Show TOC

Examples: Connecting to a DatabaseLocate this document in the navigation structure

Use

The following examples show different procedures for connecting your Java application to a database. The following example data is used:

Description

Property

Example

Name of the database user

user

MONA

Password of the database user

password

RED

Database name

-

DEMODB

Name of the database computer

servername

PARMA

SQL mode

sqlmode

ORACLE

Creating a Connection Using the java.sql.DriverManager.getConnection Method

There are several ways for transferring the connection options.

Connection Options as Part of the Connection URL

You transfer the connection options as part of the Connection URL.

"jdbc:sapdb://PARMA/DEMODB?sqlmode=ORACLE"
					

To connect to the database, call the getConnection method as follows:

java.sql.Connection conn = java.sql.DriverManager.getConnection(url, "MONA", "RED");
					

Connection Options and Logon Data As Part of the Connection URL

You transfer the connection options as well as the database user's name and the password as part of the connection URL.

"jdbc:sapdb://PARMA/DEMODB?sqlmode=ORACLE&user=MONA&password=RED"
					

To connect to the database, call the getConnection method as follows:

java.sql.Connection conn = java.sql.DriverManager.getConnection (url);
					

Using the java.util.Properties Class

The connection options, name, and password of the database user are transferred in an object of the java.util.Properties class.

The connection URL, url has the following content:

"jdbc:sapdb://PARMA/DEMODB"
					
  1. Create an object of the class java.util.Properties:

    java.util.Properties properties = new java.util.Properties ();
    							
  2. Define the connection options:

    properties.setProperty ("user", "MONA");
    properties.setProperty ("password", "RED");
    properties.setProperty ("sqlmode", "ORACLE");
    							
  3. To connect to the database, call the getConnection method as follows:

    java.sql.Connection conn = java.sql.DriverManager.getConnection (url, properties);
    							

Connecting Using the com.sap.dbtech.jdbcext.DataSourceSapDB Class

					import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import javax.sql.DataSource;
import java.sql.ResultSet;
import com.sap.dbtech.jdbcext.DataSourceSapDB;

public final class HelloDataSource
{
	public static void main (String[] args) throws SQLException
 		{
				String dbUser = "MONA";
				String password = "RED";
				String  dbName = "DEMODB";
				String  dbServer = "PARMA";
				DataSourceSapDB ds = zero;

				ds = new DataSourceSapDB();
				ds.setUser(dbUser);
				ds.setPassword(password);
				ds.setDatabaseName(dbName);
				ds.setServerName(dbServer);

				Connection c = ds.getConnection();
				Statement s = c.createStatement();
				ResultSet rs = s.executeQuery("SELECT * FROM HOTEL.CITY");
				rs.next();
				System.out.println(rs.getString(1));
				return;
		}
}