title: How to run a .sql script (from file) in Java and return a ResultSet using Spring?
body: <p>How to run a .sql script (from file) in Java and return a <code>ResultSet</code> using Spring?</p>
  
  <p>I have a program that runs <code>SQL</code> queries on a database that return <code>ResultSet</code> which I later process and use the data in my classes. I am currently using <code>JDBC</code> with the scripts inside the Java program.</p>
  
  <pre><code>StringBuilder query = new StringBuilder("some script on multiple lines");
  PreparedStatement statement = connection.prepareStatement(query.toString());
  ResultSet resultSet = statement.executeQuery();
  </code></pre>
  
  <p>I want to move the SQL queries outside of the Java program to .sql files, but I want to keep all the program logic from the <code>executeQuery</code> statements on. This means I want to have the queries return a ResultSet.</p>
  
  <p>I looked to several methods like using a <code>ScriptRunner</code>, using Spring <code>JdbcTestUtils.executeSqlScript</code> or reading the .sql file using a <code>BufferReader</code> and then passing the string to my statement. The <code>ScriptRunner</code> and the Spring <code>JdbcTestUtils.executeSqlScript</code> seem to not return a ResultSet, or I couldn't find the proper implementation. I want to stay away of the <code>BufferReader</code> method since it will require text parsing and a lot of exceptions to handle.</p>
  
  <pre><code>ScriptRunner scriptRunner = new ScriptRunner(connection, true, true);
  scriptRunner.runScript(new FileReader("script.sql"));
  </code></pre>
  
  <p>The <code>runScript</code> method returns void. Same does the <code>Spring</code> implementation:</p>
  
  <pre><code>MysqlDataSource ds = new MysqlDataSource();
  ds.setServerName("host");
  ds.setUser("user");
  ds.setPassword("password");
  
  JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
  
  Resource resource = new ClassPathResource("script.sql");
  JdbcTestUtils.executeSqlScript(jdbcTemplate, resource, true);
  </code></pre>
  
  <p>I looked thorough the <code>Spring</code> api but couldn't find something similar to what I want.
  Is there a way to load a script from file and then run it so it returns a <code>ResultSet</code> using <code>Spring</code>? I would prefer using <code>Spring</code> since it is actively mantained.</p>