Java Tutorials
  • Introduction to Java
    • What is Java?
    • History and Features of Java
    • Java Virtual Machine (JVM) and Bytecode
    • Why Java?
  • Setting up Java Development Environment
    • Installing Java Development Kit (JDK)
    • JDK vs JRE
    • Setting up IDE (Eclipse, IntelliJ, NetBeans) or Text Editor (VS Code, Sublime Text)
  • Basic Java
    • First Java Program : Hello World
    • Variable
    • Data Type
    • Constant
    • Date and Format
    • Operator
    • Condition
    • Looping
    • Function
    • Variadic Function
    • Enums
    • Array
    • Collection
    • Exception and Exception Handling
    • Naming Convention
  • Object Oriented Programming (OOP)
    • Classes and Objects
    • Inheritance and Polymorphism
    • Encapsulation and Abstraction
  • File Handling
    • Reading and Writing Binary File
    • Reading and Writing Text File
    • Serialization and Deserialization
  • Multithreading
    • Creating and Running Threads
    • Synchronization
    • Thread Pools and Executors
  • Collections API
    • Sorting and Comparable
    • Searching and Comparator
  • Java Database Connectivity (JDBC)
    • Introduction and Life Cycle
    • Connection to Database (MySQL)
    • Downloading JDBC Drivers for Various Databases
    • Maven and Gradle JDBC Drivers for Various Databases
    • JDBC URL Formats
    • Statement and PreparedStatement
    • CallableStatement
    • Selecting Data using JDBC
    • Inserting Data using JDBC
    • Updating Data using JDBC
    • Deleting Data using JDBC
    • Invoking Function and Stored Procedure using JDBC
  • Lambda
    • Introduction to Lambda Expressions
    • Functional Interface
    • Filtering, Mapping, Reducing
    • Lambda Expressions in Collections
    • Method References
    • Functional Programming Concepts
    • Stream API
    • Error Handling in Lambda Expressions
    • Optional in Functional Programming
    • Parallel Processing with Lambda
    • Functional Programming Patterns
    • Advanced Topics in Lambda Expressions
    • Best Practices and Design Patterns
    • Real-World Use Cases and Examples
Powered by GitBook
On this page
  1. Java Database Connectivity (JDBC)

Statement and PreparedStatement

1. Statement:

  • Statement is used for executing simple SQL queries without parameters.

  • Each time a statement is executed, the SQL query is parsed and optimized by the database server, which can result in performance overhead.

  • Vulnerable to SQL Injection attacks as values are directly inserted into the query string.

Advantages:

  • Suitable for static and non-repetitive queries.

  • Simpler and easier to use for straightforward queries.

Disadvantages:

  • Prone to SQL Injection attacks.

  • Potential performance issues due to parsing and optimizing the query repeatedly.

Example using Statement (Java):

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

public class StatementExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "username";
        String password = "password";

        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
             Statement statement = connection.createStatement()) {

            String sqlQuery = "SELECT * FROM users";
            ResultSet resultSet = statement.executeQuery(sqlQuery);

            while (resultSet.next()) {
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                System.out.println("Name: " + name + ", Age: " + age);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. PreparedStatement:

  • PreparedStatement is used for executing parameterized SQL queries. It allows you to create queries with placeholders (?), which are later replaced with actual values.

  • PreparedStatements are precompiled, which means they can be cached by the database server, leading to better performance.

  • Offers protection against SQL Injection attacks as parameters are treated as data, not part of the query.

Advantages:

  • Protection against SQL Injection attacks.

  • Better performance due to query caching and reuse.

Disadvantages:

  • Slightly more complex syntax.

Example using PreparedStatement (Java):

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

public class PreparedStatementExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "username";
        String password = "password";

        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
            String sqlQuery = "SELECT * FROM users WHERE age > ?";
            int minAge = 18;

            try (PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery)) {
                preparedStatement.setInt(1, minAge);

                ResultSet resultSet = preparedStatement.executeQuery();

                while (resultSet.next()) {
                    String name = resultSet.getString("name");
                    int age = resultSet.getInt("age");
                    System.out.println("Name: " + name + ", Age: " + age);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • StatementExample: Uses Statement to retrieve all data from the users table.

  • PreparedStatementExample: Uses PreparedStatement to retrieve data from the users table where age is greater than a specified value. Parameters (?) are used for values that will be replaced during execution, providing protection against SQL Injection.

PreviousJDBC URL FormatsNextCallableStatement

Last updated 1 year ago