[Java Advanced] Detailed explanation of JDBC query operation

Insert image description here

In database programming, query is a very common and important operation. JDBC (Java Database Connectivity) provides a rich API to perform various types of query operations. This blog will introduce in detail how to use JDBC for query operations, including connecting to the database, creating query statements, executing queries, processing result sets, etc. Whether you are a beginner or an experienced developer, you can get valuable information from it.

Preparation

Before performing JDBC query operations, we need to make some preparations:

  1. Install the database driver : First, make sure you have installed the JDBC driver corresponding to the database you are using. Different databases have different JDBC drivers, which you need to download and add to your project.

  2. Create a database : If you don't have a database yet, you can use a database management tool (such as MySQL Workbench) to create a database, then create a table in the database and insert some data to demonstrate query operations.

  3. Import JDBC library : In a Java project, you need to import the JDBC library, usually java.sqlthe classes and interfaces under the package.

Connect to the database

Before performing any database operations, you first need to establish a connection to the database. Connecting to the database is Connectiondone through objects. Here are the basic steps to connect to a database:

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

public class JDBCDemo {
    
    
    public static void main(String[] args) {
    
    
        // JDBC连接URL,其中mydatabase是数据库名
        String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "your_username";
        String password = "your_password";

        try {
    
    
            // 创建数据库连接
            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

            // 在此处执行查询操作

            // 关闭连接
            connection.close();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}

In the above code, we first specified the database connection URL, username and password. Then, DriverManager.getConnection()a connection to the database is created through the method and at the end the connection is closed. Please replace jdbcUrl, usernameand passwordwith your own database information.

Create query statement

Once the database connection is established, we can create the query statement. Query statements are executed using the StatementOR object. PreparedStatementHere we introduce two common ways to create query statements.

Use Statement

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

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

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

            // 创建Statement对象
            Statement statement = connection.createStatement();

            // 在此处执行查询操作

            // 关闭连接和Statement
            statement.close();
            connection.close();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}

In the above code, we connection.createStatement()create an Statementobject through methods, which is used to execute SQL statements. This method is suitable for static SQL queries.

Using PreparedStatement

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

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

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

            // 创建PreparedStatement对象,可以使用占位符
            String sql = "SELECT * FROM students WHERE age > ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // 设置占位符的值
            preparedStatement.setInt(1, 18);

            // 在此处执行查询操作

            // 关闭连接和PreparedStatement
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}

In the above code, we connection.prepareStatement()created an PreparedStatementobject using the method, which can contain placeholders. This method is suitable for situations where SQL queries need to be dynamically generated, and it also helps prevent SQL injection attacks.

Execute query

Once the query statement is created, we can perform the query operation. There are two main ways to execute queries: using executeQuery()methods to execute queries and return result sets, and using executeUpdate()methods to perform update operations.

useexecuteQuery()

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

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

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

            // 执行查询操作,将结果存储在ResultSet对象中
            String query = "SELECT * FROM students";
            ResultSet resultSet = statement.executeQuery(query);

            // 遍历结果集并处理数据
            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);
            }

            // 关闭连接、Statement和ResultSet
            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}

In the above code, we executeQuery()perform a query operation using methods and store the results in ResultSetthe object. We then ResultSetaccess each row of the query results by traversing.

useexecuteUpdate()

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

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

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

            // 执行更新操作,返回受影响的行数
            String update = "UPDATE students SET age = 20 WHERE id = 1";
            int rowsAffected = statement.executeUpdate(update);

            System.out.println("Rows affected: " + rowsAffected);

            // 关闭连接和Statement
            statement.close();
            connection.close();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}

In the above code, we use executeUpdate()the method to perform an update operation, such as updating some data in the table. It returns the number of rows affected so that we know the result of the operation.

Process result set

Once we have executed the query and obtained the result set, we need to process the result set. Common processing methods include traversing the result set, extracting data, and closing the result set.

// 遍历结果集并处理数据
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);
}

// 提取数据
if (resultSet.next()) {
    
    
    int id = resultSet.getInt("id");
    String name = resultSet.getString("name");
    int age = resultSet.getInt("age");
}

// 关闭结果集
resultSet.close();

When iterating over the result set, we use next()methods to move to the next row of the result set. Then, use getXXX()methods (for example getInt(), getString()) to extract the data. Finally, use close()the method to close the result set.

Exception handling

When doing any database operation, be sure to implement exception handling to handle potential error conditions. In the above code example, we have used try-catchblocks to catch SQLExceptionexceptions and print error messages when they occur.

try {
    
    
    // 执行数据库操作
} catch (SQLException e) {
    
    
    e.printStackTrace();
}

This ensures that problems are identified and resolved promptly when they are encountered.

Summarize

This blog introduces the basic steps of how to use JDBC to perform query operations, including connecting to the database, creating query statements, executing query operations, and processing result sets. I hope these examples can help you better understand and use JDBC for database query operations. In actual development, you can write corresponding code according to your own needs and database type to complete your needs.

Author information

Author: Fanyi
CSDN: https://techfanyi.blog.csdn.net
Nuggets: https://juejin.cn/user/4154386571867191

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/133531462