Posted In: DB2, Java Core, JDBC

DB2: Java Inserting data using stored procedure

Accesing and executing DB2 stored procedure using Java JDBC
Inserting data into sample COUNTRY table:

Table Schema:

COUNTRY_CODE VARCHAR(20)
COUNTRY_NAME VARCHAR(30)

Crating a db2 stored procedure


CREATE PROCEDURE INSERT_CITY_MAS
(IN countryCode VARCHAR(20), IN countryName VARCHAR(30))
LANGUAGE SQL
BEGIN
insert into COUNTRY values(countryCode, countryName);
END

Java CodeĀ 



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
public class TestSQLProcedure 
{
    public static void main(String[] args)
    {
        if (args.length < 1)  {
            System.out.println("Usage: ");
        }
        try
        {
            // load the DB2 Driver
            Class.forName("com.ibm.db2.jcc.DB2Driver");
            // establish a connection to DB2
            Connection db2Conn = DriverManager.getConnection("jdbc:db2://HOSTNAME:PORTNO/DB_NAME","DB_USER_NAME","PASSWORD");

            // use a statement to gather data from the database
            CallableStatement cs = db2Conn.prepareCall("{call INSERT_CITY_MAS(?, ?)}");
            // Set the value for the IN parameter
            cs.setString(1, args[0]);
            cs.setString(2, args[1]);
            // Execute the stored procedure
            cs.execute();
        cs.close();
            db2Conn.close();

        } catch (ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

by , on April 20th, 2018

  • Categories