Sunday 22 April 2012

Call mysql user define function using JAVA

mysql function :-

DELIMITER $$

DROP FUNCTION IF EXISTS `country`.`test_function`$$

CREATE DEFINER=`root`@`localhost` FUNCTION `test_function`() RETURNS int(11)
BEGIN
    declare total int;

    select count(*) into total from country;

    return total;
    END$$

DELIMITER ;



java code :-

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

public class MySqlFunction {

    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_function()}");
        int count = 0;
        pstat.registerOutParameter(1, Types.INTEGER);
        pstat.execute();
        count = pstat.getInt(1);
        System.out.println(count);
              
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

Learn more java tutorial and java blog visit : Visions Developer

No comments:

Post a Comment