SE2102 IBM DATABASE PROGRAMMING

nutmegactSoftware and s/w Development

Nov 11, 2012 (4 years and 11 months ago)

254 views

SE2102 IBM DATABASE
PROGRAMMING

Assoc
.
Prof.Dr
. Adem
Karahoca

Software
Engineering

Dept
.

1

Copyright to Adem Karahoca

Connect

to

the

IBM DB2


Add

following

jars
,
zip

and

lib

files

to

the

Libraries

section

of
your

Java
application
.


C:
\
Program
Files

(x86)
\
IBM
\
SQLLIB
\
java


db2jcc.jar


Db2java.
zip


Db2jcc4.
jar


Db2jcc_
license
_
cu
.
jar

2

Copyright to
Adem

Karahoca

Open

a IBM DB2
Connection

package javaapplication1;

import java.sql.*;

public class Main {

public static void main(String[]
args
) {


try

{


// First attempt to load the DB2 JDBC driver


Class.forName
("com.ibm.db2.jcc.DB2Driv
er");


// Now make a new connection object, and
pass your DB2 details


Connection myDB2conn =
DriverManager.getConnection
(


"jdbc:db2://localhost:50000/sample","db
2admin","123456");


// Test your connection explicitly using a
connection property

Copyright to Adem Karahoca

3

if ( myDB2conn.isClosed())

{

System.out.println
("No Connection. Check exceptions
& stack trace");

}

else

{

System.out.println
("Connected! Your DB2 JDBC code is
working");


}

// clean up connection

myDB2conn.close();

}

catch (
ClassNotFoundException

ex)

{

ex.printStackTrace
();

}

catch (
SQLException

sql_ex
)

{

sql_ex.printStackTrace
();

}


}

}


Java
Connection

Code

overview

on
Java
NetBeans

IDE


Copyright to Adem Karahoca

4

Selecting

data
from

tables

package javaapplication1;

import java.sql.*;

public class Main {


public static void main(String[]
args
) {


try

{


Class.forName
("com.ibm.db2.jcc.DB2Driver");


Connection myDB2conn =
DriverManager.getConnection
(


"jdbc:db2://localhost:50000/sample","db2ad
min","123456");


if ( myDB2conn.isClosed())


{


System.out.println
("No Connection. Check
exceptions & stack trace");


return;


}


Statement
myStmt

=
myDB2conn.createStatement();


String myQuery1 = "Select
deptname

from dept";


ResultSet

myRS1 =
myStmt.executeQuery
(myQuery1);



Copyright to Adem Karahoca

5

while (myRS1.next())


{


String
deptName

=
myRS1.getString("
deptname
");


System.out.println
(
deptName
);


}


System.out.println
("End of results
\
n");

myDB2conn.close();

}

catch (
ClassNotFoundException

ex)

{

ex.printStackTrace
();

}

catch (
SQLException

sql_ex
)

{

sql_ex.printStackTrace
();

}


}

}