Showing posts with label Database Connectivity. Show all posts
Showing posts with label Database Connectivity. Show all posts

Saturday, 30 August 2014

JDBC : JDBCRowSet Demo

Enjoying this Java Tutorial?

Subscribe to Ram N Java for regular, beginner-friendly programming tutorials and real-world coding demos!

SUBSCRIBE NOW

What is a JDBCRowSet?

In standard Java Database Connectivity (JDBC), working with standard ResultSet objects often requires manually opening connections, managing statements, and tracking resource life cycles. A JDBCRowSet wraps a standard ResultSet into a JavaBean component, making database handling flexible, easy to configure, and scrollable by default.

Key Steps to Create and Use JDBCRowSet

To implement a JdbcRowSet in your Java application, you follow these straightforward steps:

  • Obtain the RowSetProvider: Call RowSetProvider.newFactory() to obtain an instance of RowSetFactory.
  • Create JdbcRowSet: Use rowSetFactory.createJdbcRowSet() to get your row set instance.
  • Configure Connection Parameters: Set the database connection URL, username, and password using dedicated setter methods.
  • Define Query & Parameters: Set the SQL statement via setCommand() and bind query placeholders with setters like setString().
  • Execute and Process: Trigger execute() to load the records, iterate through the row set, and access column values smoothly.

Complete Java Code Example

import java.sql.SQLException;
import java.util.Scanner;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;

public class JdbcRowSetDemo {

    public static void main(String[] args) {
        JdbcRowSetDemo demo = new JdbcRowSetDemo();
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter Country Code (e.g., IND, USA): ");
            String countryCode = scanner.next();
            demo.getCityInformation(countryCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getCityInformation(String countryCode) {
        try {
            // 1. Create RowSetFactory
            RowSetFactory factory = RowSetProvider.newFactory();

            // 2. Create JdbcRowSet instance
            try (JdbcRowSet jdbcRowSet = factory.createJdbcRowSet()) {

                // 3. Set connection properties
                jdbcRowSet.setUrl("jdbc:mysql://localhost:3306/world");
                jdbcRowSet.setUsername("root");
                jdbcRowSet.setPassword("password");

                // 4. Set SQL query command and bind parameters
                jdbcRowSet.setCommand("SELECT ID, Name, CountryCode, District, Population FROM city WHERE CountryCode = ?");
                jdbcRowSet.setString(1, countryCode);

                // 5. Execute query
                jdbcRowSet.execute();

                // 6. Iterate through the records
                while (jdbcRowSet.next()) {
                    System.out.println("ID: " + jdbcRowSet.getInt("ID"));
                    System.out.println("Name: " + jdbcRowSet.getString("Name"));
                    System.out.println("CountryCode: " + jdbcRowSet.getString("CountryCode"));
                    System.out.println("District: " + jdbcRowSet.getString("District"));
                    System.out.println("Population: " + jdbcRowSet.getInt("Population"));
                    System.out.println("------------------------------------------");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Watch More Related JDBC Tutorials


Click here to watch in Youtube : https://www.youtube.com/watch?v=szmvtqQGZLQ

Click the below Image to Enlarge
JDBCRowSet 
JDBCRowSet 
JDBCRowSet 

JDBCRowSetDemo.java
import java.sql.SQLException;
import java.util.Scanner;

import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;

public class JDBCRowSetDemo
{
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL      = "jdbc:mysql://localhost:3306/world";

    // Database credentials
    static final String USERNAME    = "root";
    static final String PASSWORD    = "root";

    public static void main( String[] args )
    {
        JDBCRowSetDemo jdbcRowSetDemo = new JDBCRowSetDemo();
        Scanner scanner = new Scanner(System.in);
        while( true )
        {
            System.out.print("Enter City Country Code :");
            String cityCountrycode = scanner.nextLine();

            if( cityCountrycode.equals("exit") )
            {
                break;
            }

            jdbcRowSetDemo.getCityInformation(cityCountrycode);

        }
        scanner.close();
    }

    private void getCityInformation( String cityCountrycode )
    {
        JdbcRowSet jdbcRowSet = null;
        try
        {
            /*
             * Using RowSetFactory create the JdbcRowSet object.
             */
            RowSetFactory rowSetFactory = RowSetProvider.newFactory();
            jdbcRowSet = rowSetFactory.createJdbcRowSet();

            /*
             * Set the JdbcRowSet properties [URL,username,password,command]
             */
            jdbcRowSet.setUrl(DB_URL);
            jdbcRowSet.setUsername(USERNAME);
            jdbcRowSet.setPassword(PASSWORD);

            /*
             * Sets the command property with a query that produces a ResultSet
             * object containing all the data in the table
             */

            jdbcRowSet.setCommand("select * from city where countrycode=?");
            jdbcRowSet.setString(1, cityCountrycode);

            /*
             * The execute method does many things for you in the background:
             * 
             *  1.It makes a connection to the database using the values you assigned to the url,
             *    username, and password properties.
             *    
             *  2.It executes the query you set in the command property.
             *  
             *  3.It reads the data from the resulting ResultSet object into the jdbcRs object.
             *  
             */         
            jdbcRowSet.execute();

            /*
             *  Iterate the jdbcRowSet and get each row information
             *  of city table.
             */
            
            while( jdbcRowSet.next() )
            {
                int id = jdbcRowSet.getInt(1);
                String name = jdbcRowSet.getString(2);
                String countryCode = jdbcRowSet.getString(3);
                String district = jdbcRowSet.getString(4);
                int population = jdbcRowSet.getInt(5);

                /*
                 * Display values
                 */
                System.out.print("ID: " + id);
                System.out.print(", Name: " + name);
                System.out.print(", CountryCode: " + countryCode);
                System.out.print(", District: " + district);
                System.out.println(", Population: " + population);
            }
            
        }
        catch( SQLException se )
        {
            se.printStackTrace();
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }   
        
        finally
        {
            if(jdbcRowSet!=null)
            {
                try
                {
                    jdbcRowSet.close();
                }
                catch( SQLException e )
                {
                    e.printStackTrace();
                }
            }
        }

    }
}

Output
Enter City Country Code :ind
ID: 1024, Name: Mumbai (Bombay), CountryCode: IND, District: Maharashtra, Population: 10500000
ID: 1025, Name: Delhi, CountryCode: IND, District: Delhi, Population: 7206704
ID: 1026, Name: Calcutta [Kolkata], CountryCode: IND, District: West Bengali, Population: 4399819
ID: 1027, Name: Chennai (Madras), CountryCode: IND, District: Tamil Nadu, Population: 3841396

---
---


Enter City Country Code :pak
ID: 2822, Name: Karachi, CountryCode: PAK, District: Sindh, Population: 9269265
ID: 2823, Name: Lahore, CountryCode: PAK, District: Punjab, Population: 5063499
ID: 2824, Name: Faisalabad, CountryCode: PAK, District: Punjab, Population: 1977246
ID: 2825, Name: Rawalpindi, CountryCode: PAK, District: Punjab, Population: 1406214

---
---

Enter City Country Code :exit

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download /JDBCRowSet_Read_DemoApp Project Click the below link

https://sites.google.com/site/javaee4321/jdbc/JDBCRowSet_Read_DemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Saturday, 9 August 2014

    Type 1 JDBC Driver : JDBC-ODBC Bridge Driver (Bridge Driver)

    Master Java Database Connectivity!

    Subscribe to Ram N Java for in-depth JDBC guides, architectural insights, and clear Java tutorials!

    SUBSCRIBE NOW

    What is the Type 1 JDBC Driver?

    The Type 1 JDBC Driver, commonly known as the JDBC-ODBC Bridge Driver, acts as a translator between Java's JDBC calls and Open Database Connectivity (ODBC) function calls.

    During the early days of Java, native JDBC drivers were not available for every database. The Type 1 driver bridged this gap by translating JDBC API calls into native ODBC calls, allowing Java applications to communicate with any database that provided an ODBC driver.

    How the Architecture Works

    The execution flow follows a sequential bridge path across layers:

    • Java Application: Issues standard JDBC calls via java.sql interfaces.
    • JDBC-ODBC Bridge: Translates standard JDBC method calls into corresponding ODBC function calls using native methods.
    • ODBC Driver & Database Client: The client-side ODBC driver processes the queries and routes them to the database server.
    • Database: Executes SQL statements and returns result sets back through the bridge layers.

    Advantages and Limitations

    • Broad Database Support (Historic): Allowed Java applications to connect easily to legacy databases that only supported ODBC (e.g., MS Access).
    • Platform Dependency: Requires ODBC configuration and native client binaries installed on every client machine, breaking pure Java portability.
    • Performance Overhead: Dual-layer translation (JDBC to ODBC and ODBC to database format) degrades execution speed.
    • Deprecation: The JDBC-ODBC Bridge was deprecated in Java 7 and completely removed starting from Java 8 in favor of pure Java Type 4 drivers.

    Watch More Related JDBC Tutorials


    Click here to watch in Youtube : https://www.youtube.com/watch?v=np3TQe9mE0o

    Click the below Image to Enlarge
    Type 1 JDBC Driver : JDBC-ODBC Bridge Driver (Bridge Driver)
    Type 1 JDBC Driver : JDBC-ODBC Bridge Driver (Bridge Driver)
    Type 1 JDBC Driver : JDBC-ODBC Bridge Driver (Bridge Driver)
    Type 1 JDBC Driver : JDBC-ODBC Bridge Driver (Bridge Driver)

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Sunday, 13 July 2014

    JDBC PreparedStatement Demo

    Master Java Database Connectivity!

    Subscribe to Ram N Java for practical code walkthroughs, JDBC best practices, and beginner-friendly Java tutorials!

    SUBSCRIBE NOW

    What is a PreparedStatement in JDBC?

    The PreparedStatement interface extends Statement and represents a precompiled SQL statement. Instead of constructing SQL strings by concatenating values directly, PreparedStatement uses placeholders (?) for parameterized queries.

    Because the database compiles the query structure once and reuses the execution plan with different parameters, it offers superior performance for repeated queries and provides strong defense against SQL injection attacks.

    Complete Java Code Implementation

    Here is a practical example demonstrating how to insert records using PreparedStatement:

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    public class PreparedStatementDemo {
        public static void main(String[] args) {
            String url = "jdbc:mysql://localhost:3306/testdb";
            String user = "root";
            String password = "password";
    
            String insertQuery = "INSERT INTO employees (id, name, department, salary) VALUES (?, ?, ?, ?)";
    
            try (Connection conn = DriverManager.getConnection(url, user, password);
                 PreparedStatement pstmt = conn.prepareStatement(insertQuery)) {
    
                // Setting parameter values
                pstmt.setInt(1, 101);
                pstmt.setString(2, "Alice Smith");
                pstmt.setString(3, "Engineering");
                pstmt.setDouble(4, 85000.00);
    
                int rowsInserted = pstmt.executeUpdate();
                System.out.println("Rows successfully inserted: " + rowsInserted);
    
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    Key Advantages of PreparedStatement

    • SQL Injection Prevention: Values set via setter methods are automatically sanitized, neutralizing malicious SQL input.
    • Better Performance: Precompiled queries can be executed multiple times with varying parameter inputs without recompilation overhead.
    • Cleaner Code: Eliminates cumbersome quotation mark concatenation and string formatting when assembling complex SQL commands.

    Watch More Related JDBC Tutorials


    Click here to watch in Youtube : https://www.youtube.com/watch?v=g0EauGjVY58

    Click the below Image to Enlarge

    JDBCPreparedStatementDemo Project Dir Structure

    JDBCPreparedStatementDemo.java
    
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class JDBCPreparedStatementDemo
    {
        // JDBC driver name and database URL
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL      = "jdbc:mysql://localhost:3306/world";
    
        // Database credentials
        static final String USERNAME    = "root";
        static final String PASSWORD    = "root";
    
        public static void main( String[] args )
        {
    
            JDBCPreparedStatementDemo jdbcPreparedStatementDemo =  
                                            new JDBCPreparedStatementDemo();
            jdbcPreparedStatementDemo.getCityInformation();
    
        }
    
        private void getCityInformation()
        {
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            try
            {
                /*
                 * Register the JDBC driver in DriverManager
                 */
    
                Class.forName(JDBC_DRIVER);
    
                /*
                 * Establish connection to the Database using DriverManager
                 */
    
                connection = DriverManager
                        .getConnection(DB_URL, USERNAME, PASSWORD);
    
                String sql = "select * from city where countryCode=? and District = ?";
    
                /*
                 * Execute the query
                 */
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, "GBR");
                preparedStatement.setString(2, "England");
    
                ResultSet rs = preparedStatement.executeQuery();
    
                while( rs.next() )
                {
                    int id = rs.getInt(1);
                    String name = rs.getString(2);
                    String countryCode = rs.getString(3);
                    String district = rs.getString(4);
                    int population = rs.getInt(5);
    
                    /*
                     * Display values
                     */
                    System.out.print("ID: " + id);
                    System.out.print(", Name: " + name);
                    System.out.print(", CountryCode: " + countryCode);
                    System.out.print(", District: " + district);
                    System.out.println(", Population: " + population);
                }
    
                rs.close();
    
            }
            catch( SQLException se )
            {
                /*
                 * Handle errors for JDBC
                 */
                se.printStackTrace();
            }
            catch( ClassNotFoundException e )
            {
                /*
                 * Handle errors for Class.forName
                 */
                e.printStackTrace();
            }
            finally
            {
                /*
                 * finally block used to close resources
                 */
                try
                {
                    if( preparedStatement != null )
                    {
                        preparedStatement.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
                try
                {
                    if( connection != null )
                    {
                        connection.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
            }
    
        }
    
    }
    
    
    Output
    ID: 456, Name: London, CountryCode: GBR, District: England, Population: 7285000
    ID: 457, Name: Birmingham, CountryCode: GBR, District: England, Population: 1013000
    ID: 459, Name: Liverpool, CountryCode: GBR, District: England, Population: 461000
    ID: 461, Name: Sheffield, CountryCode: GBR, District: England, Population: 431607
    ID: 462, Name: Manchester, CountryCode: GBR, District: England, Population: 430000
    ID: 463, Name: Leeds, CountryCode: GBR, District: England, Population: 424194
    ID: 464, Name: Bristol, CountryCode: GBR, District: England, Population: 402000
    ID: 466, Name: Coventry, CountryCode: GBR, District: England, Population: 304000
    ID: 467, Name: Leicester, CountryCode: GBR, District: England, Population: 294000
    ID: 468, Name: Bradford, CountryCode: GBR, District: England, Population: 289376
    ID: 470, Name: Nottingham, CountryCode: GBR, District: England, Population: 287000
    ID: 471, Name: Kingston upon Hull, CountryCode: GBR, District: England, Population: 262000
    ID: 472, Name: Plymouth, CountryCode: GBR, District: England, Population: 253000
    ID: 473, Name: Stoke-on-Trent, CountryCode: GBR, District: England, Population: 252000
    ID: 474, Name: Wolverhampton, CountryCode: GBR, District: England, Population: 242000
    ID: 475, Name: Derby, CountryCode: GBR, District: England, Population: 236000
    ID: 477, Name: Southampton, CountryCode: GBR, District: England, Population: 216000
    ID: 479, Name: Northampton, CountryCode: GBR, District: England, Population: 196000
    ID: 480, Name: Dudley, CountryCode: GBR, District: England, Population: 192171
    ID: 481, Name: Portsmouth, CountryCode: GBR, District: England, Population: 190000
    ID: 482, Name: Newcastle upon Tyne, CountryCode: GBR, District: England, Population: 189150
    ID: 483, Name: Sunderland, CountryCode: GBR, District: England, Population: 183310
    ID: 484, Name: Luton, CountryCode: GBR, District: England, Population: 183000
    ID: 485, Name: Swindon, CountryCode: GBR, District: England, Population: 180000
    ID: 486, Name: Southend-on-Sea, CountryCode: GBR, District: England, Population: 176000
    ID: 487, Name: Walsall, CountryCode: GBR, District: England, Population: 174739
    ID: 488, Name: Bournemouth, CountryCode: GBR, District: England, Population: 162000
    ID: 489, Name: Peterborough, CountryCode: GBR, District: England, Population: 156000
    ID: 490, Name: Brighton, CountryCode: GBR, District: England, Population: 156124
    ID: 491, Name: Blackpool, CountryCode: GBR, District: England, Population: 151000
    ID: 493, Name: West Bromwich, CountryCode: GBR, District: England, Population: 146386
    ID: 494, Name: Reading, CountryCode: GBR, District: England, Population: 148000
    ID: 495, Name: Oldbury/Smethwick (Warley), CountryCode: GBR, District: England, Population: 145542
    ID: 496, Name: Middlesbrough, CountryCode: GBR, District: England, Population: 145000
    ID: 497, Name: Huddersfield, CountryCode: GBR, District: England, Population: 143726
    ID: 498, Name: Oxford, CountryCode: GBR, District: England, Population: 144000
    ID: 499, Name: Poole, CountryCode: GBR, District: England, Population: 141000
    ID: 500, Name: Bolton, CountryCode: GBR, District: England, Population: 139020
    ID: 501, Name: Blackburn, CountryCode: GBR, District: England, Population: 140000
    ID: 503, Name: Preston, CountryCode: GBR, District: England, Population: 135000
    ID: 504, Name: Stockport, CountryCode: GBR, District: England, Population: 132813
    ID: 505, Name: Norwich, CountryCode: GBR, District: England, Population: 124000
    ID: 506, Name: Rotherham, CountryCode: GBR, District: England, Population: 121380
    ID: 507, Name: Cambridge, CountryCode: GBR, District: England, Population: 121000
    ID: 508, Name: Watford, CountryCode: GBR, District: England, Population: 113080
    ID: 509, Name: Ipswich, CountryCode: GBR, District: England, Population: 114000
    ID: 510, Name: Slough, CountryCode: GBR, District: England, Population: 112000
    ID: 511, Name: Exeter, CountryCode: GBR, District: England, Population: 111000
    ID: 512, Name: Cheltenham, CountryCode: GBR, District: England, Population: 106000
    ID: 513, Name: Gloucester, CountryCode: GBR, District: England, Population: 107000
    ID: 514, Name: Saint Helens, CountryCode: GBR, District: England, Population: 106293
    ID: 515, Name: Sutton Coldfield, CountryCode: GBR, District: England, Population: 106001
    ID: 516, Name: York, CountryCode: GBR, District: England, Population: 104425
    ID: 517, Name: Oldham, CountryCode: GBR, District: England, Population: 103931
    ID: 518, Name: Basildon, CountryCode: GBR, District: England, Population: 100924
    ID: 519, Name: Worthing, CountryCode: GBR, District: England, Population: 100000
    ID: 520, Name: Chelmsford, CountryCode: GBR, District: England, Population: 97451
    ID: 521, Name: Colchester, CountryCode: GBR, District: England, Population: 96063
    ID: 522, Name: Crawley, CountryCode: GBR, District: England, Population: 97000
    ID: 523, Name: Gillingham, CountryCode: GBR, District: England, Population: 92000
    ID: 524, Name: Solihull, CountryCode: GBR, District: England, Population: 94531
    ID: 525, Name: Rochdale, CountryCode: GBR, District: England, Population: 94313
    ID: 526, Name: Birkenhead, CountryCode: GBR, District: England, Population: 93087
    ID: 527, Name: Worcester, CountryCode: GBR, District: England, Population: 95000
    ID: 528, Name: Hartlepool, CountryCode: GBR, District: England, Population: 92000
    ID: 529, Name: Halifax, CountryCode: GBR, District: England, Population: 91069
    ID: 530, Name: Woking/Byfleet, CountryCode: GBR, District: England, Population: 92000
    ID: 531, Name: Southport, CountryCode: GBR, District: England, Population: 90959
    ID: 532, Name: Maidstone, CountryCode: GBR, District: England, Population: 90878
    ID: 533, Name: Eastbourne, CountryCode: GBR, District: England, Population: 90000
    ID: 534, Name: Grimsby, CountryCode: GBR, District: England, Population: 89000
    
    
    Environment Used 

    JDK version :1.7.0_51
    Tomcat version : 7.0.50 

    To Download JDBCPreparedStatementDemoApp Project Click the below link

    https://sites.google.com/site/javaee4321/jdbc/JDBCPreparedStatementDemoApp.zip?attredirects=0&d=1

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Tutorials