How to Execute SQL Statements from a File in Java
To execute SQL statements in a file using the Connection object, you can follow these steps:
- Open a connection to your database using the appropriate driver and connection string.
- Create a Connection object using the connection.
- Create a FileReader object to read the SQL file.
- Create a BufferedReader object using the FileReader object to read the file line by line.
- Iterate through each line of the file and execute the SQL statement using the Connection object's execute() method.
- Close the BufferedReader and FileReader objects.
- 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 著作权归作者所有。请勿转载和采集!