Data Types and Operators
(Non-Primitive Data Types)
Control Flow Statements
Conditional Statements
Looping Statements
Branching Statements
Object-Oriented Programming (OOP)
Exception Handling
Collections Framework
Overview of Collections
Java I/O
Multithreading
GUI Programming with Swing
Advanced Topics
JAVA CODE
Java Basics
Working with Objects
Arrays, Conditionals, and Loops
Creating Classes and Applications in Java
More About Methods
Java Applet Basics
Graphics, Fonts, and Color
Simple Animation and Threads
More Animation, Images, and Sound
Managing Simple Events and Interactivity
Creating User Interfaces with the awt
Windows, Networking, and Other Tidbits
Modifiers, Access Control, and Class Design
Packages and Interfaces
Exceptions
Multithreading
Streams and I/O
Using Native Methods and Libraries
Under the Hood
Java Programming Tools
Working with Data Structures in Java
Advanced Animation and Media
Fun with Image Filters
Client/Server Networking in Java
Emerging Technologies
appendix A :- Language Summary
appendix B :- Class Hierarchy Diagrams
appendix C The Java Class Library
appendix D Bytecodes Reference
appendix E java.applet Package Reference
appendix F java.awt Package Reference
appendix G java.awt.image Package Reference
appendix H java.awt.peer Package Reference
appendix I java.io Package Reference
appendix J java.lang Package Reference
appendix K java.net Package Reference
appendix L java.util Package Reference

Executing SQL queries in Java involves several steps, including establishing a connection to the database, creating a statement, executing the query, and processing the results. Here’s a detailed description of the process with examples:

1. Setup: Add JDBC Driver

First, you need to add the JDBC driver for your database to your project. For example, if you are using MySQL, you can add the MySQL Connector/J JAR file to your project.

2. Import Required Packages

Import the necessary JDBC packages:

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

				
			

3. Establish a Connection

Establish a connection to the database using ‘DriverManager.getConnection‘:

				
					String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

Connection connection = null;

try {
    connection = DriverManager.getConnection(url, user, password);
    if (connection != null) {
        System.out.println("Connected to the database!");
    }
} catch (SQLException e) {
    e.printStackTrace();
}

				
			

4. Create a Statement

Create a Statement object to send SQL statements to the database:

				
					Statement statement = null;

try {
    statement = connection.createStatement();
} catch (SQLException e) {
    e.printStackTrace();
}

				
			

5. Execute a Query

Execute a SQL query using the executeQuery method for SELECT statements or executeUpdate for INSERT, UPDATE, and DELETE statements.

Example of a SELECT Query:

				
					String query = "SELECT id, name, age FROM users";
ResultSet resultSet = null;

try {
    resultSet = statement.executeQuery(query);

    // Process the results
    while (resultSet.next()) {
        int id = resultSet.getInt("id");
        String name = resultSet.getString("name");
        int age = resultSet.getInt("age");

        System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    // Close the ResultSet
    if (resultSet != null) {
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

				
			

Example of an INSERT Query:

				
					String insertQuery = "INSERT INTO users (name, age) VALUES ('John Doe', 30)";
int rowsAffected = 0;

try {
    rowsAffected = statement.executeUpdate(insertQuery);
    System.out.println("Rows affected: " + rowsAffected);
} catch (SQLException e) {
    e.printStackTrace();
}

				
			

6. Close the Connection

Finally, close the Statement and Connection objects to free up resources:

				
					if (statement != null) {
    try {
        statement.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

if (connection != null) {
    try {
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

				
			

Full Example

Here’s the complete code combining all the steps:

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

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database";
        String user = "your_username";
        String password = "your_password";

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // Establish connection
            connection = DriverManager.getConnection(url, user, password);

            if (connection != null) {
                System.out.println("Connected to the database!");

                // Create statement
                statement = connection.createStatement();

                // Execute SELECT query
                String query = "SELECT id, name, age FROM users";
                resultSet = statement.executeQuery(query);

                // Process results
                while (resultSet.next()) {
                    int id = resultSet.getInt("id");
                    String name = resultSet.getString("name");
                    int age = resultSet.getInt("age");

                    System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
                }

                // Execute INSERT query
                String insertQuery = "INSERT INTO users (name, age) VALUES ('Jane Doe', 25)";
                int rowsAffected = statement.executeUpdate(insertQuery);
                System.out.println("Rows affected: " + rowsAffected);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // Close resources
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

				
			

This example demonstrates how to connect to a MySQL database, execute a SELECT query to retrieve data, and execute an INSERT query to insert data into the database. Adjust the connection details and SQL queries according to your database schema and requirements.

Scroll to Top