Showing posts with label JDBC. Show all posts
Showing posts with label JDBC. Show all posts

Monday, July 18, 2011

Change the fetch size on the result set

package org.best.examples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
  public static void main(String[] argv) throws Exception {

    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);

    // Get the fetch size of a statement
    Statement stmt = connection.createStatement ();
    int fetchSize = stmt.getFetchSize();

    // Set the fetch size on the statement
    stmt.setFetchSize(100);

    // Create a result set
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Change the fetch size on the result set
    resultSet.setFetchSize(100);

  }
}

Sunday, July 17, 2011

Check if cursor is in the first row

package org.best.examples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
  public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager
        .getConnection("jdbc:mysql://localhost/testdb", "root", "");

    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = statement.executeQuery("SELECT * FROM products");

    if (resultSet.isBeforeFirst()) {
      System.out.println("beginning");
    }
    connection.close();
  }
}

Saturday, July 16, 2011

Getting the Cursor Position in a Scrollable Result Set

package org.best.examples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Get cursor position
    int pos = resultSet.getRow();
    boolean b = resultSet.isBeforeFirst();

    // Move cursor to the first row
    resultSet.next();

    // Get cursor position
    pos = resultSet.getRow();
    b = resultSet.isFirst();

    // Move cursor to the last row
    resultSet.last();

    // Get cursor position
    pos = resultSet.getRow();
    b = resultSet.isLast();

    // Move cursor past last row
    resultSet.afterLast();

    // Get cursor position
    pos = resultSet.getRow();
    b = resultSet.isAfterLast();

  }
}

Friday, July 15, 2011

Move cursor up 3 rows from the current row. If this moves cursor beyond the first row, cursor is put before the first row

package org.best.examples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    // Create a scrollable result set
    Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Move cursor forward
    while (resultSet.next()) {
      // Get data at cursor
      String s = resultSet.getString(1);
    }

    // Move cursor backward
    while (resultSet.previous()) {
      // Get data at cursor
      String s = resultSet.getString(1);
    }

    // Move cursor up 3 rows from the current row. If this moves cursor beyond the first row, cursor is put before the first row
    resultSet.relative(-3);

  }
}

Thursday, July 14, 2011

Determining If a Database Supports Scrollable Result Sets

package org.best.examples;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    DatabaseMetaData dmd = connection.getMetaData();
    if (dmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE)) {
        System.out.println("Insensitive scrollable result sets are supported");
    }
    if (dmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE)) {
        System.out.println("Sensitive scrollable result sets are supported");
    }
    if (!dmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE)
        && !dmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE)) {
        System.out.println("Updatable result sets are not supported");
    }
  }
}   

Wednesday, July 13, 2011

Move Cursor to the First Row

package org.best.examples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    // Create a scrollable result set
    Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Move cursor forward
    while (resultSet.next()) {
      // Get data at cursor
      String s = resultSet.getString(1);
    }

    // Move cursor backward
    while (resultSet.previous()) {
      // Get data at cursor
      String s = resultSet.getString(1);
    }

    // Move cursor to the first row
    resultSet.first();

  }
}

Tuesday, July 12, 2011

Move cursor backward

package org.best.examples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    // Create a scrollable result set
    Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Move cursor forward
    while (resultSet.next()) {
      // Get data at cursor
      String s = resultSet.getString(1);
    }

    // Move cursor backward
    while (resultSet.previous()) {
      // Get data at cursor
      String s = resultSet.getString(1);
    }


  }
}

Monday, July 11, 2011

Get Number Of Rows in a Scrollable ResultSet from MySQL

package org.best.examples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class GetNumberOfRowsScrollableResultSet_MySQL {

  public static Connection getConnection() throws Exception {
    String driver = "org.gjt.mm.mysql.Driver";
    String url = "jdbc:mysql://localhost/databaseName";
    String username = "root";
    String password = "root";
    Class.forName(driver);
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }

  public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      conn = getConnection();
      String query = "select id from employees";
      stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

      rs = stmt.executeQuery(query);
      // extract data from the ResultSet scroll from top
      while (rs.next()) {
        String id = rs.getString(1);
        System.out.println("id=" + id);
      }
      // move to the end of the result set
      rs.last();
      // get the row number of the last row which is also the row count
      int rowCount = rs.getRow();
      System.out.println("rowCount=" + rowCount);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        rs.close();
        stmt.close();
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
}

Friday, June 10, 2011

How to Call Procedure

package org.best.example;

import java.sql.*;
public class CallableStmt
    {
     public static void main(String args[])
         {
         try
             {
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             Connection con = DriverManager.getConnection("jdbc:odbc:uma","kworker","kworker");
           
             //calling a stored procedure with no input/output param
             /*
             CREATE PROCEDURE HELLOWORLD
             AS
             SELECT 'HELLOWORLD' AS HELLO
             */
             CallableStatement cs1 = con.prepareCall("{call HelloWorld}");
             ResultSet rs1 = cs1.executeQuery();
             while(rs1.next())
                 {
                 String one = rs1.getString("HELLO");
                 System.out.println(one);
             }
           
           
             //Calling a stored procedure which takes in 2 parameters for addition
             /*
             --EXECUTE ADDITION 10,25,NULL
             ALTER PROCEDURE ADDITION
             @A INT
             , @B INT
             , @C INT OUT
             AS
             SELECT @C = @A + @B
             */
             CallableStatement cs2 = con.prepareCall("{call ADDITION(?,?,?)}");
             cs2.registerOutParameter(3,java.sql.Types.INTEGER);
             cs2.setInt(1,10);
             cs2.setInt(2,25);
             cs2.execute();
             int res = cs2.getInt(3);
             System.out.println(res);
           
             //Another way
             /*
             --create table test(slno int,ques varchar(100),ans text)
             --EXECUTE fetchRec 1
             create procedure fetchRec
             @A int
             as
             select * from test where slno=@A
             */
             CallableStatement cs3 = con.prepareCall("{call fetchRec(?)}");
             cs3.registerOutParameter(1,java.sql.Types.INTEGER);
             cs3.setInt(1,5);
             ResultSet rs3 = cs3.executeQuery();
             while(rs3.next())
                 {
                 String ques = rs3.getString(2);
                 String ans = rs3.getString(3);
                 System.out.println(ques);
                 System.out.println(ans);
             }
           
           
         }
         catch(Exception e)
             {
             e.printStackTrace();
         }
     }
}

Thursday, June 9, 2011

How to Call Procedure without Callable

package org.best.example;
import java.sql.*;
    class ProcedureCalling {
         public static void main(String args[]){
             try{
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             Connection con=DriverManager.getConnection("jdbc:odbc:test1","sa","password");
             String sql= "{ call procname(?) }"; // procname is name of procedure
             cst=con.prepareCall(sql);
             int i=1;
             cst.registerOutParameter(1,Types.NUMERIC,0);
             cst.setInt(1,i);
             cst.executeUpdate();
             i=cst.getInt(1);
         }catch(Exception proc)
             { System.out.println("error ine executed query is :" + proc);
     } }
}
}

Wednesday, June 8, 2011

how to Insert an Image into SQL Server


package org.best.example;

import java.sql.*;
public class InsertBlob_SQLServer
    {
     static Connection conn = null;
   
     public InsertBlob_SQLServer()
         {
         try
             {
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             conn = DriverManager.getConnection("jdbc:odbc:javaxxx", "userid", "pwd");
         }
         catch(Exception e)
             {
             e.printStackTrace();
         }
     }
     public static void main(String[] args)
         {
         InsertBlob_SQLServer insertBlob1 = new InsertBlob_SQLServer();
         if(args.length != 2)
             {
             System.out.println("Usage: java InsertBlob_SQLServer FileName File");
             System.out.println("Example: java InsertBlob_SQLServer myImage.jpg \"C:\\\\MyFolder\\\\myImage.jpg\"");
         }
         else
             {
             try
                 {
                 insertBlob1.insPic(conn, args[0], args[1]);
             }
             catch(Exception e)
                 {
                 e.printStackTrace();
             }
             finally
                 {
                 insertBlob1 = null;
             }
         }
     }
   
     private void insPic(Connection c, String name, String fName)
         {
         try
             {
             File f = new File(fName);
             FileInputStream in = new FileInputStream(f);
             byte[] image = new byte[(int) f.length()];
             in.read(image);
             // Below: the question marks are IN parameter placeholders.
             String sql = "INSERT INTO testImage VALUES(?,?)";
             PreparedStatement stmt = c.prepareStatement(sql);
             stmt.setString(1, name);
             stmt.setBytes(2, image);
             stmt.executeUpdate();
             stmt.close();
         }
         catch (SQLException e)
             {
             System.out.print(e.getMessage());
         }
         catch (IOException e)
             {
             System.out.print(e.getMessage());
         }
     }
}
//create table testImage(fname varchar(100),img image)

Tuesday, June 7, 2011

How to Get Column Names for a Table

For Fetching column names of a table ResultSetMetaData is used in JDBC .

package org.best.examples;

import java.sql.*;

public class GetColNames
    {
   
    public static void main(String args[])
        {
         try
             {
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             Connection connection = DriverManager.getConnection("jdbc:odbc:dd","","");
             // Create a result set
             Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM test");
           
             // Get result set meta data
             ResultSetMetaData rsmd = rs.getMetaData();
             int numColumns = rsmd.getColumnCount();
           
             // Get the column names; column indices start from 1
             for (int i=1; i                 {
                 String columnName = rsmd.getColumnName(i);
               
                 // Get the name of the column's table name
                 String tableName = rsmd.getTableName(i);
                 System.out.println("columnName "+columnName);
             }
         }
         catch (Exception e)
             {
             System.out.println(e);
         }
    }
}