To execute SQL statements in a file using the Connection object, you can follow these steps:

  1. Open a connection to your database using the appropriate driver and connection string.
  2. Create a Connection object using the connection.
  3. Create a FileReader object to read the SQL file.
  4. Create a BufferedReader object using the FileReader object to read the file line by line.
  5. Iterate through each line of the file and execute the SQL statement using the Connection object's execute() method.
  6. Close the BufferedReader and FileReader objects.
  7. Close the Connection object.

Here's an example code snippet in Java:

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

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

        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
            String sqlFilePath = "path/to/sql/file.sql";
            FileReader fileReader = new FileReader(sqlFilePath);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            Statement statement = connection.createStatement();

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                statement.execute(line);
            }

            bufferedReader.close();
            fileReader.close();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Make sure to replace the jdbcUrl, username, and password with your own database connection details, and sqlFilePath with the actual path to your SQL file.


原文地址: http://www.cveoy.top/t/topic/pIXy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录