Friday, August 21, 2015

callable statement 2

import java.sql.*;
import java.util.Scanner;
 
public class Mysql_callableDemo
{
    public static void main(String[] args)
    {
        int i;
        try
        {
            Scanner s = new Scanner(System.in);
            System.out.println("Enter ID");
            i=s.nextInt();
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Driver is loaded");
            Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2all","root","kamal");
            System.out.println("Connection created");
            String q = "call datainfo(?,?,?,?)";
            CallableStatement cs = c.prepareCall(q);
            cs.setInt(1,i);
            cs.registerOutParameter(2, Types.VARCHAR);
            cs.registerOutParameter(3, Types.VARCHAR);
            cs.registerOutParameter(4, Types.INTEGER);
            cs.execute();
            String nm = cs.getString(2);
            String ct = cs.getString(3);
            int age = cs.getInt(4);
            System.out.println("Name = "+nm);
            System.out.println("City = "+ct);
            System.out.println("Age  = "+age); 
        }
        catch(Exception e)
        {
            System.out.println("Exception : " +e);
        }  
    }
}

 
Output:
 
Enter ID
1
Driver is loaded
Connection created
Name = java
City = abc
Age  = 300
For closing the connection in each and every program of JDBC we should call the method close() through Connection object c.close();
As my friend suggest me we should call close() method to close our connection with database from finally block so close() method will execute in all circumstances.
Even if a try block has an exception our connection will be closed safely.
EXample with finally block:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.sql.*;
public class MysqlDemo
{
    public static void main(String[] args) throws SQLException
    {
                Connection c = null;
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Driver is loaded");
            c = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2all","root","root");
            System.out.println("Connection created");
            Statement s = c.createStatement();
            ResultSet rs = s.executeQuery("select * from data");
            System.out.println("ID\tName\tCity\tAge");
             
            while(rs.next()) // Retrieve data from ResultSet
            {          
                             System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4));
            }
             
        }
        catch(Exception e)
        {
            System.out.println("Exception : " +e);
        }
                finally
                {
                       c.close();
                }
    }
 
}

No comments:

Post a Comment