Access DB2 database in standalone Java project
I need to access DB开发者_如何学Go2 database in plain standalone Java project.
I cannot use datasource from container right? Do I need to write JDBC connection?
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
JDBC connection
Depending on your needs, either handle a JDBC connection yourself or use a standalone JDBC pool e.g. C3P0, DBCP or BoneCP.
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
精彩评论