Wednesday, 30 July 2014

JDBC Batch Processing [Statement] Demo

Enjoyed this tutorial?

Subscribe to Ram N Java for regular, beginner-friendly Java & database tutorials!

▶ Subscribe Now

What is Batch Processing with Statement?

In standard database programming, executing individual SQL statements one after another leads to high network traffic and significant communication overhead. JDBC solves this with Batch Processing, allowing you to bundle multiple heterogeneous SQL statements (such as INSERT, UPDATE, or DELETE) together and send them to the database in a single round-trip using a standard Statement object.

Core Methods of the Statement Interface

  • addBatch(String sql): Adds a complete, standalone SQL statement to the batch execution queue.
  • executeBatch(): Sends all bundled SQL commands to the database engine at once and returns an integer array (int[]) showing the update count for each executed query.
  • clearBatch(): Empties the current batch buffer if you need to discard queued statements.

Step-by-Step Code Walkthrough

Here is how you can create and execute a batch consisting of diverse SQL operations:

Statement statement = connection.createStatement();

// Queue multiple DML statements into the batch
statement.addBatch("INSERT INTO city VALUES (4082, 'San Jose', 'USA', 'California', 1020000)");
statement.addBatch("INSERT INTO city VALUES (4083, 'Austin', 'USA', 'Texas', 960000)");
statement.addBatch("UPDATE city SET Population = 1030000 WHERE ID = 4082");

// Execute the entire batch in a single network call
int[] results = statement.executeBatch();

for (int count : results) {
    System.out.println("Rows affected: " + count);
}

Statement vs PreparedStatement for Batching

While PreparedStatement is optimized for executing the same parameterized query repeatedly with different values, standard Statement batching is great when you need to send different, non-parameterized SQL commands together in a unified network batch.

Recommended Related Tutorials

Expand your JDBC knowledge with these essential tutorials:


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

Click the below Image to Enlarge

JDBCBatchProcessDemo Project Dir Structure
JDBC Batch Processing [Statement] Demo

JDBC Batch Processing [Statement] Demo

JDBCBatchProcess.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCBatchProcess
{
    // 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)
    {
        JDBCBatchProcess JDBCBatchProcess = new JDBCBatchProcess();
        JDBCBatchProcess.addCityInformation();
    }

    private void addCityInformation()
    {
        Connection connection = null;
        Statement statement = 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);

            /*
             * Set auto-commit to false
             */
            connection.setAutoCommit(false);

            String sql1 = "insert into city values(5000,'Bangalore','IND','Karnataka',400000)";
            String sql2 = "insert into city values(5001,'Channai','IND','TamilNadu',200000)";
            String sql3 = "insert into city values(5002,'Thiruvanathapuram','IND','Kerala',800000)";

            /*
             * Execute the query
             */
            statement = connection.createStatement();

            /*
             * Add sql's to the batch
             */
            statement.addBatch(sql1);
            statement.addBatch(sql2);
            statement.addBatch(sql3);

            int result[] = statement.executeBatch();

            /*
             * Explicitly commit statements to apply changes
             */
            connection.commit();

            for (int i = 0; i < result.length; i++)
            {
                System.out.println(result[i]);
            }

        }
        catch (SQLException se)
        {
            /*
             * Handle errors for JDBC
             */
            try
            {
                connection.rollback();
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }
            se.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            /*
             * Handle errors for Class.forName
             */
            e.printStackTrace();
        }
        catch (Exception e)
        {
            try
            {
                connection.rollback();
            }
            catch (SQLException e1)
            {

                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        finally
        {
            /*
             * finally block used to close resources
             */
            try
            {
                if (statement != null)
                {
                    statement.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
            try
            {
                if (connection != null)
                {
                    connection.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
        }

    }
}

Output
1
1
1

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download JDBCBatchProcessDemo_Statement_App Project Click the below link

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

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • JDBC Batch Processing - Introduction

    Want to Master Java & Database Programming?

    Subscribe to our YouTube channel for clear, step-by-step developer tutorials and interview tips!

    SUBSCRIBE NOW

    The Problem with Individual Query Execution

    In real-world applications, your Java program typically runs on an application server, while the relational database resides on a separate database server across the network.

    When you execute multiple SQL commands—such as 100 insert or update statements—the traditional approach is to send each query individually over the network, wait for execution, receive the response, and then repeat the process.

    Sending queries one by one introduces heavy network communication overhead, causes database round-trip delays, and drastically decreases the overall performance of your enterprise application.

    What is JDBC Batch Processing?

    Batch Processing in JDBC provides an elegant and high-performance solution to this problem. Instead of dispatching queries individually, it allows you to bundle multiple related SQL statements together into a single "batch" and transmit the entire collection to the database server in a single network call.

    By executing queries together in a batch:

    • Reduces Network Traffic: Only one round trip over the network is required for the entire collection of statements.
    • Boosts Execution Speed: Database engines optimize execution when processing grouped write operations.
    • Improves Application Throughput: Database connection threads spend less time waiting on client transmissions.

    Core Batch Processing Methods in JDBC

    Both the Statement and PreparedStatement interfaces provide built-in methods dedicated to managing batches:

    • addBatch(String sql): Adds an individual SQL statement to the active batch list (used with Statement). When using PreparedStatement, call addBatch() after binding your parameters.
    • executeBatch(): Sends the collected batch of commands to the database server for execution. It returns an int[] array where each element contains the update count for the corresponding command.
    • clearBatch(): Clears all queued commands from the batch buffer, releasing resources and resetting the statement for future operations.

    When to Use Batch Processing

    Batch processing is the standard best practice whenever you are performing:

    1. Bulk data imports or migrations (such as loading CSV or Excel records into tables).
    2. Mass data updates or deletions across large database tables.
    3. Transactional business operations requiring atomic execution of multiple changes.

    Related Tutorials You Might Like


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

    Click the below Image to Enlarge
    JDBC Batch Processing - Introduction
    JDBC Batch Processing - Introduction
    JDBC Batch Processing - Introduction
    JDBC Batch Processing - Introduction
    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Monday, 28 July 2014

    JDBC Drop Table Demo

    Enjoyed this tutorial?

    Subscribe to Ram N Java for regular, beginner-friendly Java & database tutorials!

    ▶ Subscribe Now

    What is DROP TABLE in JDBC?

    In SQL, the DROP TABLE statement is a Data Definition Language (DDL) command used to permanently remove an existing table structure along with all its data, indexes, constraints, and triggers from a database.

    Using Java Database Connectivity (JDBC), you can automate database administration tasks and execute DDL operations directly from your Java programs using the Statement interface.

    Executing DDL Commands Using executeUpdate()

    While executeQuery() is reserved for queries that return rows (like SELECT), DDL commands such as CREATE, ALTER, and DROP are run using executeUpdate() or execute():

    • executeUpdate(String sql): Executes given SQL commands. For DDL operations (like DROP TABLE), it returns 0.
    • Safe Dropping: Use DROP TABLE IF EXISTS table_name to prevent SQL syntax exceptions if the table does not exist.

    Step-by-Step Code Walkthrough

    Here is a complete, beginner-friendly example of establishing a connection and dropping a table cleanly:

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    
    public class DropTableDemo {
        public static void main(String[] args) {
            String url = "jdbc:mysql://localhost:3306/jdbcdb";
            String username = "root";
            String password = "password";
    
            String sql = "DROP TABLE IF EXISTS student";
    
            try (Connection con = DriverManager.getConnection(url, username, password);
                 Statement stmt = con.createStatement()) {
    
                stmt.executeUpdate(sql);
                System.out.println("Table dropped successfully!");
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    Important Best Practices

    1. Irreversible Operation: Dropping a table cannot be rolled back in most databases once committed. Double-check table names before execution.
    2. Foreign Key Constraints: If other tables reference the target table via foreign keys, ensure dependent child tables or constraints are handled first.
    3. Resource Management: Always close Statement and Connection objects using try-with-resources to avoid memory and connection leaks.

    Recommended Related Tutorials

    Continue expanding your Java and database management skills with these practical guides:


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

    Click the below Image to Enlarge

    JDBCDropTableDemo Project Dir Structure
    JDBC Drop Table Demo
    JDBC Drop Table Demo
    JDBCDropTable.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    public class JDBCDropTable
    {
        // 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 )    
        {
    
            JDBCDropTable jdbcDropTable = new JDBCDropTable();
            jdbcDropTable.dropTable();
    
        }
    
        private void dropTable()
        {
            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 = "DROP TABLE REGISTRATION";
    
                /*
                 * Execute the query
                 */
                preparedStatement = connection.prepareStatement(sql);
    
                int returnValue = preparedStatement.executeUpdate();
    
                System.out.println("returnValue : " + returnValue);
    
                System.out.println("Table 'REGISTRATION' has been dropped");
    
            }
            catch( SQLException se )
            {
                /*
                 * Handle errors for JDBC
                 */
                se.printStackTrace();
            }
            catch( ClassNotFoundException e )
            {
                /*
                 * Handle errors for Class.forName
                 */
                e.printStackTrace();
            }
            catch( Exception e )
            {
                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
    returnValue : 0
    Table 'REGISTRATION' has been dropped
    
    
    Environment Used 

    JDK version : 1.7.0_51
    Mysql Server version : 5.6.19 

    To Download JDBCDropTableDemoApp Project Click the below link

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

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • JDBC Create Table Demo

    Enjoyed this tutorial?

    Subscribe to Ram N Java for regular, beginner-friendly Java & database tutorials!

    ▶ Subscribe Now

    What is CREATE TABLE in JDBC?

    In relational database management systems (RDBMS) like MySQL, the CREATE TABLE statement is a Data Definition Language (DDL) command used to define the schema, column names, data types, and integrity constraints of a new table.

    With Java Database Connectivity (JDBC), you can automate table creation programmatically right from your Java application without needing external SQL clients.

    Executing DDL Using executeUpdate()

    To execute SQL DDL commands like CREATE TABLE, Java provides the executeUpdate() method on the Statement interface:

    • executeUpdate(String sql): Executes the given SQL statement. For DDL operations that return nothing, it returns 0.
    • Safe Execution: Adding CREATE TABLE IF NOT EXISTS prevents runtime errors if the target table already exists in the database.

    Step-by-Step Code Walkthrough

    Here is a clear, complete example showing how to connect to MySQL and create a new table:

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    
    public class CreateTableDemo {
        public static void main(String[] args) {
            String url = "jdbc:mysql://localhost:3306/jdbcdb";
            String username = "root";
            String password = "password";
    
            String sql = "CREATE TABLE IF NOT EXISTS student ("
                       + "id INT PRIMARY KEY AUTO_INCREMENT, "
                       + "name VARCHAR(50) NOT NULL, "
                       + "age INT, "
                       + "email VARCHAR(100)"
                       + ")";
    
            try (Connection con = DriverManager.getConnection(url, username, password);
                 Statement stmt = con.createStatement()) {
    
                stmt.executeUpdate(sql);
                System.out.println("Table created successfully!");
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    Key Best Practices

    1. Choose Appropriate Data Types: Match database column types (e.g., INT, VARCHAR) properly to your application domain data models.
    2. Define Primary Keys: Always designate a primary key column to ensure uniqueness and optimize query indexing.
    3. Automatic Resource Cleanup: Use the try-with-resources statement to ensure both Connection and Statement are safely closed.

    Recommended Related Tutorials

    Continue building your database programming skills with these step-by-step guides:


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

    Click the below Image to Enlarge

    JDBCCreateTableDemo Project Dir Structure
    JDBC Create Table Demo
    JDBC Create Table Demo
    JDBCCreateTable.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    public class JDBCCreateTable
    {
        // 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 )
        {
    
            JDBCCreateTable jdbcCreateTable = new JDBCCreateTable();
            jdbcCreateTable.createTable();
    
        }
    
        private void createTable()
        {
            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 = "CREATE TABLE REGISTRATION " + "(id INT not NULL, "
                        + " first VARCHAR(255), " + " last VARCHAR(255), "
                        + " age INT, " + " PRIMARY KEY ( id ))";
    
                System.out.println(sql);
    
                /*
                 * Execute the query
                 */
                preparedStatement = connection.prepareStatement(sql);
    
                int returnValue = preparedStatement.executeUpdate();
    
                System.out.println("returnValue : " + returnValue);
    
                System.out.println("Table REGISTRATION has been created");
    
            }
            catch( SQLException se )
            {
                /*
                 * Handle errors for JDBC
                 */
                se.printStackTrace();
            }
            catch( ClassNotFoundException e )
            {
                /*
                 * Handle errors for Class.forName
                 */
                e.printStackTrace();
            }
            catch( Exception e )
            {
                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
    CREATE TABLE REGISTRATION (id INT not NULL,  first VARCHAR(255),  last VARCHAR(255),  age INT,  PRIMARY KEY ( id ))
    returnValue : 0
    Table REGISTRATION has been created
    

    Environment Used 

    JDK version :1.7.0_51
    Tomcat version : 7.0.50 

    To Download JDBCCreateTableDemoApp Project Click the below link

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

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • JDBC Drop Database Demo

    Enjoying Java & Database Tutorials?

    Subscribe to Ram N Java on YouTube for clear, beginner-friendly programming lessons!

    🔔 Subscribe to Channel

    How to Drop a Database Using JDBC in Java

    Deleting an entire database is an administrative task that requires precision. In SQL, you remove a database using the DROP DATABASE statement. When automating database maintenance through Java, JDBC (Java Database Connectivity) allows you to execute this query programmatically.

    The SQL Drop Command

    The standard SQL command to remove a database is straightforward:

    DROP DATABASE students;

    Executing this query immediately removes the students database along with all its tables and records.

    Step-by-Step Java Implementation

    Here is the standard workflow to drop a database using JDBC:

    1. Register the Driver: Load the database driver using Class.forName().
    2. Establish a Connection: Connect to the database server using DriverManager.getConnection() without specifying a particular database name in the URL (connect at server level).
    3. Prepare the Statement: Create a PreparedStatement or Statement object containing the DROP DATABASE command.
    4. Execute the Query: Call executeUpdate() to send the command to the database engine.
    5. Clean Up Resources: Always close the statement and database connection in a finally block or use try-with-resources.

    Watch More JDBC Tutorials


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

    Click the below Image to Enlarge

    JDBCDropDatabaseDemo Project Dir Structure
    JDBC Drop Database Demo
    JDBC Drop Database Demo

    JDBCDropDatabase.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    public class JDBCDropDatabase
    {
        // JDBC driver name and database URL
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL      = "jdbc:mysql://localhost:3306/";
    
        // Database credentials
        static final String USERNAME    = "root";
        static final String PASSWORD    = "root";
    
        public static void main( String[] args )
        {
    
            JDBCDropDatabase jdbcDropDatabase = new JDBCDropDatabase();
            jdbcDropDatabase.dropDatabase();
    
        }
    
        private void dropDatabase()
        {
            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 = "DROP DATABASE STUDENTS";
    
                /*
                 * Execute the query
                 */
                preparedStatement = connection.prepareStatement(sql);
                            
                int returnValue = preparedStatement.executeUpdate();
    
                System.out.println("returnValue : " + returnValue);
                
                System.out.println("STUDENTS database has been Droped");
    
            }
            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
    returnValue : 0
    STUDENTS database has been Droped
    
    
    Environment Used 

    JDK version : 1.7.0_51
    Mysql Server version : 5.6.19 

    To Download JDBCDropDatabaseDemoApp Project Click the below link

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

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Saturday, 26 July 2014

    JDBC Create Database Demo

    Enjoying Java & Database Tutorials?

    Subscribe to Ram N Java on YouTube for beginner-friendly coding lessons and demos!

    🔔 Subscribe to Channel

    How to Create a Database Using JDBC in Java

    When developing Java applications that manage relational data, you often need to set up new database instances programmatically. Using JDBC (Java Database Connectivity), you can send standard SQL DDL (Data Definition Language) commands straight from your Java code to create a brand new database on your server.

    The SQL Create Database Statement

    In SQL, initializing a new database requires a single instruction:

    CREATE DATABASE students;

    This query tells the database engine to allocate storage and register a new catalog named students.

    Step-by-Step Java Implementation

    Here is the standard workflow to create a database dynamically using JDBC:

    1. Register the JDBC Driver: Load your database vendor driver class into memory using Class.forName().
    2. Connect at Server Level: Connect to the database server host without referencing a specific database name in the connection URL string.
    3. Create a Statement: Instantiate a Statement or PreparedStatement to hold your DDL query.
    4. Execute the Statement: Invoke executeUpdate() to create the database on the server.
    5. Close Resources: Ensure both connection and statement objects are properly closed in a finally block or via try-with-resources.

    Watch More JDBC Tutorials


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

    Click the below Image to Enlarge

    JDBCCreateDatabaseDemo Project Dir Structure
    JDBC Create Database Demo
    JDBC Create Database Demo
    JDBCCreateDatabase.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    public class JDBCCreateDatabase
    {
        // JDBC driver name and database URL
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL = "jdbc:mysql://localhost:3306/";
    
        // Database credentials
        static final String USERNAME = "root";
        static final String PASSWORD = "root";
    
        public static void main(String[] args)
        {
    
            JDBCCreateDatabase jdbcCreateDatabase = new JDBCCreateDatabase();
            jdbcCreateDatabase.createDatabase();
    
        }
    
        private void createDatabase()
        {
            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 = "CREATE DATABASE STUDENTS";
    
                /*
                 * Execute the query
                 */
                preparedStatement = connection.prepareStatement(sql);
    
                int returnValue = preparedStatement.executeUpdate();
    
                System.out.println("returnValue : " + returnValue);
    
            }
            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
    returnValue : 1
    

    Environment Used 

    JDK version : 1.7.0_51
    Mysql Server version : 5.6.19 

    To Download JDBCCreateDatabaseDemoApp Project Click the below link

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

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Friday, 25 July 2014

    JDBC Sorting Data Demo

    Enjoying Java & Database Tutorials?

    Subscribe to Ram N Java on YouTube for beginner-friendly coding lessons and practical demos!

    🔔 Subscribe to Channel

    How to Sort Database Records Using JDBC in Java

    Organizing data in a meaningful order is essential when displaying records to users. While Java collections can sort data in memory, letting the database engine handle sorting using SQL's ORDER BY clause is far more efficient. Through JDBC (Java Database Connectivity), you can easily execute queries that fetch sorted rows into a ResultSet.

    The SQL ORDER BY Clause

    To sort records, append the ORDER BY keyword followed by the target column name and sort direction:

    SELECT id, first_name, last_name, age FROM students ORDER BY age ASC;

    Use ASC for ascending order (default) or DESC for descending order.

    Step-by-Step Java Implementation

    Follow these standard steps to retrieve and display sorted records using JDBC:

    1. Establish Connection: Connect to your target database schema using DriverManager.getConnection().
    2. Create Statement: Instantiate a Statement or PreparedStatement with your sorting query.
    3. Execute Query: Call executeQuery() to obtain the sorted ResultSet.
    4. Iterate Results: Use a while (resultSet.next()) loop to read and display the organized column data.
    5. Close Resources: Ensure the ResultSet, Statement, and Connection are closed using try-with-resources.

    Watch More JDBC Tutorials


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

    Click the below Image to Enlarge

    JDBCSortingDataDemo Project Dir Structure
    JDBC Sorting Data Demo
    JDBC Sorting Data Demo

    JDBCSortingData.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Scanner;
    
    public class JDBCSortingData
    {
        // 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)
        {
    
            JDBCSortingData jdbcSortingData = new JDBCSortingData();
    
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter Asc or Desc Order :");
            while (scanner.hasNext())
            {
                String orderby = scanner.nextLine();
                if (orderby.equalsIgnoreCase("Exit"))
                {
                    break;
                }
                jdbcSortingData.getCityInformation(orderby);
                System.out.print("Enter Asc or Desc Order :");
            }
    
            scanner.close();
    
        }
    
        private void getCityInformation(String orderby)
        {
            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;
                if (orderby.equalsIgnoreCase("asc"))
                {
                    sql = "select * from city order by name asc";
                }
                else
                {
                    sql = "select * from city order by name desc";
                }
    
                System.out.println("sql : " + sql);
    
                /*
                 * Execute the query
                 */
                preparedStatement = connection.prepareStatement(sql);
    
                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("Name: " + name);
                    System.out.print(",ID: " + id);
                    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();
            }
            catch (Exception e)
            {
                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
    Enter Asc or Desc Order :asc
    sql : select * from city order by name asc
    Name: A Coruña (La Coruña),ID: 670, CountryCode: ESP, District: Galicia, Population: 243402
    Name: Aachen,ID: 3097, CountryCode: DEU, District: Nordrhein-Westfalen, Population: 243825
    Name: Aalborg,ID: 3318, CountryCode: DNK, District: Nordjylland, Population: 161161
    Name: Aba,ID: 2760, CountryCode: NGA, District: Imo & Abia, Population: 298900
    Name: Abadan,ID: 1404, CountryCode: IRN, District: Khuzestan, Population: 206073
    Name: Abaetetuba,ID: 395, CountryCode: BRA, District: Pará, Population: 111258
    Name: Abakan,ID: 3683, CountryCode: RUS, District: Hakassia, Population: 169200
    Name: Abbotsford,ID: 1849, CountryCode: CAN, District: British Colombia, Population: 105403
    Name: Abeokuta,ID: 2747, CountryCode: NGA, District: Ogun, Population: 427400
    Name: Aberdeen,ID: 478, CountryCode: GBR, District: Scotland, Population: 213070
    Name: Abha,ID: 3191, CountryCode: SAU, District: Asir, Population: 112300
    
    ---
    ---
    
    
    Enter Asc or Desc Order :desc
    sql : select * from city order by name desc
    Name: [San Cristóbal de] la Laguna,ID: 698, CountryCode: ESP, District: Canary Islands, Population: 127945
    Name: Zytomyr,ID: 3446, CountryCode: UKR, District: Zytomyr, Population: 297000
    Name: Zwolle,ID: 28, CountryCode: NLD, District: Overijssel, Population: 105819
    Name: Zwickau,ID: 3145, CountryCode: DEU, District: Saksi, Population: 104146
    Name: Zunyi,ID: 2025, CountryCode: CHN, District: Guizhou, Population: 261862
    Name: Zumpango,ID: 2669, CountryCode: MEX, District: México, Population: 99781
    Name: Zukovski,ID: 3756, CountryCode: RUS, District: Moskova, Population: 96500
    Name: Zonguldak,ID: 3404, CountryCode: TUR, District: Zonguldak, Population: 111542
    Name: Zoetermeer,ID: 26, CountryCode: NLD, District: Zuid-Holland, Population: 110214
    Name: Zlatoust,ID: 3671, CountryCode: RUS, District: Tšeljabinsk, Population: 196900
    Name: Zixing,ID: 2207, CountryCode: CHN, District: Hunan, Population: 110048
    
    ---
    ---
    
    Enter Asc or Desc Order :exit
    
    
    Environment Used 

    JDK version : 1.7.0_51
    Mysql Server version : 5.6.19 

    To Download JDBCSortingDataDemoApp Project Click the below link

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

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:
    Newer Posts Older Posts Home

    Tutorials