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 |
server |
PARMA |
SQL mode |
sqlmode |
ORACLE |
There are several ways for transferring the connection options.
You transfer the connection options as part of the Connection URL.
Syntax
"jdbc:sapdb://PARMA/DEMODB?sqlmode=ORACLE"
To connect to the database, call the getConnection method as follows:
Syntax
java.sql.Connection conn = java.sql.DriverManager.getConnection(url, "MONA", "RED");
You transfer the connection options as well as the database user’s name and the password as part of the connection URL.
Syntax
"jdbc:sapdb://PARMA/DEMODB?sqlmode=ORACLE&user=MONA&password=RED"
To connect to the database, call the getConnection method as follows:
Syntax
java.sql.Connection conn = java.sql.DriverManager.getConnection (url);
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:
Syntax
"jdbc:sapdb://PARMA/DEMODB"
Create an object of the class java.util.Properties:
Syntax
java.util.Properties properties = new java.util.Properties ();
Define the connection options:
Syntax
properties.setProperty ("user", "MONA"); properties.setProperty ("password", "RED"); properties.setProperty ("sqlmode", "ORACLE");
To connect to the database, call the getConnection method as follows:
Syntax
java.sql.Connection conn = java.sql.DriverManager.getConnection (url, properties);
Syntax
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.setServer(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; } }