I\'m trying to write a bit of code that reads a SQL file (multiple CREATE TABLE
statements separated by ;
) and executes all the statements.
In
try it
public void executeSqlScript(Connection connection,StringBuffer sql)throws SQLException{
try {
connection.setAutoCommit(false);//设置为手工提交模式
ScriptUtils.executeSqlScript(connection, new ByteArrayResource(sql.toString().getBytes()));
connection.commit();//提交事务
} catch (SQLException e) {
connection.rollback();
}finally{
connection.close();
}
}
We can also achive through SQLExec. Below code is working for me.
import java.io.File;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
public class Test {
public static void main(String[] args) {
Test t = new Test();
t.executeSql("");
}
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("test1.sql"));
executer.setDriver("org.postgresql.Driver");
executer.setPassword("postgres");
executer.setUserid("postgres");
executer.setUrl("jdbc:postgresql://localhost/test");
executer.execute();
}
}
Maybe Spring's ScriptUtils will be useful in your case. Especially executeSqlScript
methods.
Note that DEFAULT_STATEMENT_SEPARATOR
has a default value of ';'
(see Constant Field Values)
I've solved the issue this way:
public void createDefaultDB(DataSource dataSource) {
Resource resource = new ClassPathResource("CreateDefaultDB.sql");
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(resource);
databasePopulator.execute(dataSource);
}
You can inject DataSource
as usual:
import javax.sql.DataSource;
//...
@Autowired
private DataSource dataSource;