Sunday 22 April 2012

Call Mysql procedure from JAVA

mysql procedure :-

DELIMITER $$

DROP PROCEDURE IF EXISTS `country`.`test_country`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `test_country`(
        IN  p_id                           INT(11)       ,
        IN  p_country_name                      VARCHAR(30)
     )
BEGIN
    INSERT INTO country
    (id,name)
    VALUES
         (
           p_id,
           p_country_name
         ) ;
    END$$

DELIMITER ;


java code :

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;


public class MySqlProcedure {

    static Connection connection = null;
    static CallableStatement pstat = null;
    static String connectionURL = "jdbc:mysql://localhost:3306/country";
   
    public static void main(String[] args) {
        try{
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection(connectionURL,"root","dreams");
        pstat = connection.prepareCall("{ call test_country(?,?)}"); // test_country is procedure name
        pstat.setInt(1, 5);
        pstat.setString(2, "test");
        pstat.executeUpdate();
       
        }catch(Exception e){
            e.printStackTrace();
        }

    }

}

Learn more java tutorial and java blog visit : Visions Developer

No comments:

Post a Comment