How can JDBC execute an insert statement?

JDBC (Java Database Connectivity) is a Java API used for carrying out database operations. To execute an INSERT statement, you can utilize the PreparedStatement interface in JDBC.

Below is a sample code demonstrating how to use JDBC to execute an INSERT statement.

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

public class Main {
    public static void main(String[] args) {
        // 数据库连接信息
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "root";
        String password = "password";

        // INSERT语句
        String insertQuery = "INSERT INTO mytable (column1, column2) VALUES (?, ?)";

        try (Connection connection = DriverManager.getConnection(url, username, password);
             PreparedStatement statement = connection.prepareStatement(insertQuery)) {

            // 设置参数
            statement.setString(1, "value1");
            statement.setString(2, "value2");

            // 执行INSERT语句
            int rowsAffected = statement.executeUpdate();

            System.out.println("插入成功,影响行数:" + rowsAffected);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

In the above code, we start by establishing a database connection and creating a precompiled SQL statement using the PreparedStatement interface. Next, we use the setXXX() method to set the value of the parameters (where XXX represents the type of parameter, for example setString() is used to set a string parameter value). Finally, we call the executeUpdate() method to execute the INSERT statement and retrieve the number of affected rows.

Please note that the above example is just a simple demonstration and does not consider error handling and closing connection resources. In actual applications, proper handling of exceptions should be implemented and connections should be closed after using them to prevent resource leaks.

bannerAds