We have to follow 6 steps to play with DB2 database in java jdbc.
Note: We have use “db2jcc_license_cu-version.jar” and “db2jcc-version.jar” ex- “db2jcc_license_cu-1.0.jar” and “db2jcc-1.0.jar”
Step 1: Create table in database
CREATE TABLE USER_DETAILS (
USER_ID INTEGER,
USER_NAME VARCHAR(50) NOT NULL,
PASSWORD VARCHAR(50) NOT NULL,
PRIMARY KEY(USER_ID)
)
Step 2: Load the Driver class
“com.ibm.db2.jcc.DB2Driver” using below syntax –
Step 3: Get connection by using below url –
"jdbc:db2://localhost:port/databasename", "username", "password"
Step 4: Create Statement or PreparedStatement –
Step 5: Execute the query-
Step 6: Iterate the result set-
Example-
Note: We have use “db2jcc_license_cu-version.jar” and “db2jcc-version.jar” ex- “db2jcc_license_cu-1.0.jar” and “db2jcc-1.0.jar”
Step 1: Create table in database
CREATE TABLE USER_DETAILS (
USER_ID INTEGER,
USER_NAME VARCHAR(50) NOT NULL,
PASSWORD VARCHAR(50) NOT NULL,
PRIMARY KEY(USER_ID)
)
Step 2: Load the Driver class
“com.ibm.db2.jcc.DB2Driver” using below syntax –
Class.forName("com.ibm.db2.jcc.DB2Driver");
Step 3: Get connection by using below url –
"jdbc:db2://localhost:port/databasename", "username", "password"
Connection connection=DriverManager.getConnection("jdbc:db2://localhost:port/databasename", "username", "password");
Step 4: Create Statement or PreparedStatement –
PreparedStatement prepareStatement = connection.prepareStatement("SELECT * FROM USER_DETAILS");
Step 5: Execute the query-
ResultSet resultSet = prepareStatement.executeQuery();
Step 6: Iterate the result set-
while (resultSet.next()) { System.out.println("UserName:"+resultSet.getString("NAME") + "," + ("UserPassword:"+resultSet.getString("PASSWORD")); }
Example-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import java.sql.*; class MySqlTest { public static void main(String[] args)throws Exception { Class.forName("com.ibm.db2.jcc.DB2Driver"); Connection connection=DriverManager.getConnection("jdbc:db2://localhost:port/databasename", "username", "password"); PreparedStatement prepareStatement = connection.prepareStatement("SELECT * FROM USER_DETAILS"); ResultSet resultSet = prepareStatement.executeQuery(); while (resultSet.next()) { System.out.println("UserName:"+resultSet.getString("NAME")+","+("UserPassword:"+ resultSet.getString("PASSWORD") ); } resultSet.close(); prepareStatement.close(); connection.close(); } } |
No comments :
Post a Comment