Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Execute SQL Script File in Java?

I want to execute an SQL script file in Java without reading the entire file content into a big query and executing it.

Is there any other standard way?

like image 229
Vladimir Avatar asked Jan 15 '10 13:01

Vladimir


People also ask

Can you do SQL in Java?

What you will probably be doing is using JDBC to allow Java to connect to SQL databases. There are also persistence layers, such as Hibernate, that you can use to store and retrieve data in a database using Java.


1 Answers

There is great way of executing SQL scripts from Java without reading them yourself as long as you don't mind having a dependency on Ant. In my opinion such a dependency is very well justified in your case. Here is sample code, where SQLExec class lives in ant.jar:

private void executeSql(String sqlFilePath) {     final class SqlExecuter extends SQLExec {         public SqlExecuter() {             Project project = new Project();             project.init();             setProject(project);             setTaskType("sql");             setTaskName("sql");         }     }      SqlExecuter executer = new SqlExecuter();     executer.setSrc(new File(sqlFilePath));     executer.setDriver(args.getDriver());     executer.setPassword(args.getPwd());     executer.setUserid(args.getUser());     executer.setUrl(args.getUrl());     executer.execute(); } 
like image 169
Ruslans Uralovs Avatar answered Sep 29 '22 12:09

Ruslans Uralovs