I have a abc.sql file containing procedure and insert statements . How can i run the script(abc.sql file) using java code without using script Runner API.
-
Which database are you using?Sai Ye Yan Naing Aye– Sai Ye Yan Naing Aye2016-05-26 05:50:03 +00:00Commented May 26, 2016 at 5:50
-
I find some solution. You can get it at coderanch.com/t/306966/JDBC/databases/Execute-sql-file-javaThanhLD– ThanhLD2016-05-26 06:47:03 +00:00Commented May 26, 2016 at 6:47
Add a comment
|
1 Answer
Use ProcessBuilder. Below sample code, I run select query and print the result in console.
public class RunOracleSql {
public static void main(String[] args) {
final String fileExtension = ".sql";
String script_location = "C:/SQLFileLocation";
try {
File file = new File("C:/SQLFileLocation");
File[] listFiles = file.listFiles(new FileFilter() {
public boolean accept(File f) {
if (f.getName().toLowerCase().endsWith(fileExtension))
return true;
return false;
}
});
for (int i = 0; i < listFiles.length; i++) {
script_location = "@" + listFiles[i].getAbsolutePath();// ORACLE
ProcessBuilder processBuilder = new ProcessBuilder("sqlplus",
"username/password@database_name", script_location); // ORACLE
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String currentLine = null;
while ((currentLine = in.readLine()) != null) {
System.out.println(" " + currentLine);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}