Posted by
test
|
Posted on
7:41 AM
Category:
DB2 connectivity
JAVA sample code to connect to DB2 Database using Type 4 Driver
The below sample code shows the simple way of making connection to a DB2 Server Database exists on a remote machine with out installing any db2 client on your machine. But all we need to have is Type 4 drivers to make this connection which we can use by pointing to the
db2jcc.jar and
db2jcc_license_cu.jar.
All we need to do is point the java class path to find this jars, in case of eclipse users configure the build path and these 2 jars as external jars from the path they located to the project. change the Host name, port, user name and password like details in the below program and run accordingly.
Syntax for the connection string : DriverManager.getConnection
("jdbc:db2j:net://<HOSTNAME>:/,">","");
Sample connection string : DriverManager.getConnection
("jdbc:db2j:net://nc184120.tivlab.austin.ibm.com:50001/CDSDB","db2inst1","db2inst1");
The following is the sample code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Java2DB2 {
public static void main(String[] args)
{
try
{
// load the DB2 Driver
Class.forName("com.ibm.db2.jcc.DB2Driver");
// establish a connection to DB2
Connection db2Conn =
DriverManager.getConnection
("jdbc:db2j:net://nc184120.tivlab.austin.ibm.com:50001/CDSDB","db2inst1","db2inst1");
// use a statement to gather data from the database
Statement st = db2Conn.createStatement();
String myQuery = "SELECT * FROM CDSSCHEMA.ACL_ADMIN";
// execute the query
ResultSet resultSet = st.executeQuery(myQuery);
// cycle through the resulSet and display what was grabbed
while (resultSet.next())
{
String name = resultSet.getString("USER_NAME");
String id = resultSet.getString("USER_ID");
System.out.println("User Name: " + name);
System.out.println("User ID: " + id);
System.out.println("-------------------------------");
}
// clean up resources
resultSet.close();
st.close();
db2Conn.close();
}
catch (ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
}
Comments (0)
Post a Comment