import java.sql.*;
import java.io.*;
public class SQLExecutor {
public static void main(String[] args) {
String jdbcUrl = "jdbc:sqlite:mydatabase.db"; // Example for SQLite, an embedded database
String sqlFilePath = "path/to/your/script.sql";
try (Connection conn = DriverManager.getConnection(jdbcUrl);
Statement stmt = conn.createStatement();
BufferedReader reader = new BufferedReader(new FileReader(sqlFilePath))) {
String line;
StringBuilder sqlCommand = new StringBuilder();
while ((line = reader.readLine()) != null) {
// Ignore comments and empty lines
if (line.trim().isEmpty() || line.trim().startsWith("--")) {
continue;
}
sqlCommand.append(line);
// Assuming statements are terminated by a semicolon
if (line.trim().endsWith(";")) {
stmt.execute(sqlCommand.toString());
sqlCommand = new StringBuilder(); // Reset for the next command
}
}
System.out.println("SQL script executed successfully.");
} catch (SQLException e) {
System.err.println("SQL Error: " + e.getMessage());
} catch (IOException e) {
System.err.println("File I/O Error: " + e.getMessage());
}
}
}
No comments:
Post a Comment