views:

46

answers:

4

I need to access DB2 database in plain standalone Java project.

I cannot use datasource from container right? Do I need to write JDBC connection?

+1  A: 

JDBC connection

zengr
+1  A: 

You need to have necessary db2 JDBC jars in your program's compile time, runtime classpath. If you have native DB2 client installed on target machines, you may use JDBC ODBC Bridge. However, best to stick with pure Java- type4 drivers. (db2jcc.jar, db2jcc_license*.jar etc)

Once the drivers are in classpath, you may use usual JDBC code to start with. Such as:

import java.sql.*;
import java.lang.*;
import java.io.*;
import Com.ibm.db2.jcc.*;  //Type4 library
public class DB2Sample{
  static
  {
    try 
    {       

      Class.forName("com.ibm.db2.jcc.DB2Driver");
    } 
    catch (ClassNotFoundException e)
    {
       System.err.println("Could not load DB2 driver \n");
       System.err.println(e.getMessage());
       System.exit(1);
    }

public static void main(String args[]) 
  {

    /* Type 4 driver url */
    String url = "jdbc:db2j:net://machine-name:port-number/TGSAMPLE";
         Connection conn = DriverManager.getConnection(url,"userid", "psswrd");
...
  }

and so on.

Look at IBM documentation here for better examples and details

ring bearer
I am geting this exception:java.sql.SQLException: No suitable driver,I am using the same calss. Any idea
Ensure that you have the required JAR files in your CLASSPATH. How are you running the example?Also, make sure you have right parameters for connection - such as url, user and password; Can you share your code?
ring bearer
+1  A: 

Depending on your needs, either handle a JDBC connection yourself or use a standalone JDBC pool e.g. C3P0, DBCP or BoneCP.

Pascal Thivent
A: 

I cannot use datasource from container right? Do I need to write JDBC connection?

You can try to get the connection from the container using JNDI Lookup. For instance see this.

But I think it would be much easier not do it.

Do I need to write JDBC connection?

Yes, if it's easier for you to manage the connection your self.

You can also use a connection pool such as Apache DBCP or C3PO. Here's a list of others that support Connection pooling for standalone app

OscarRyz