
package tickets;

import java.sql.*;

/**
 * This test will show that there is a difference in using a PreparedStatement
 * or a CallableStatement with a stored procedure. The difference is that
 * the ResultSet returned by a CallableStatement contains the right data and
 * the ResultSet returned by a PreparedStatement contains scrambled data.
 * @author Matthias Hanisch
 */
public class Ticket25381 {

    public static void main(String[] args) {
        try
        {
            DriverManager.registerDriver((Driver)Class.forName("com.mysql.jdbc.Driver").newInstance());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        try {
            Connection con=DriverManager.getConnection("jdbc:mysql://sk:3307/dbd_test_reports2", "root", "inet");
            DatabaseMetaData dbmd=con.getMetaData();
            System.out.println("Database:\t"+dbmd.getDatabaseProductName()+"\t"+dbmd.getDatabaseProductVersion());
            System.out.println("Driver:\t"+dbmd.getDriverName()+"\t"+dbmd.getDriverVersion());
            PreparedStatement cstmt;
            boolean useCallableStatement=true;
            while(true) {
                if(useCallableStatement) {
                    System.out.println("Results of CallableStatement");
                    cstmt=con.prepareCall("{call sp_test(?)}");
                }
                else {
                    System.out.println("Results of PreparedStatement");
                    cstmt=con.prepareStatement("{call sp_test(?)}");
                }
                cstmt.setInt(1, 1);
                ResultSet rs=cstmt.executeQuery();
                ResultSetMetaData rsmd=rs.getMetaData();
                int columnCount=rsmd.getColumnCount();
                while(rs.next()) {
                    for(int i=0;i<columnCount;i++) {
                        System.out.print(rsmd.getCatalogName(i+1)+"="+rs.getObject(i+1));
                        System.out.print('\t');
                    }
                    System.out.println();
                }
                rs.close();
                cstmt.close();
                if(useCallableStatement) {
                    useCallableStatement=false;
                }
                else {
                    break;
                }
            }
            con.close();
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }

}
