Preface
As we all know, there are many ways to call SQL scripts in Java. Here, I only record one method I use often. I personally think it is quite practical and convenient.
Use the ScriptRunner class.
The ScriptRunner class is used to execute SQL statements, such as creating a database schema, or passing in a default or test database, etc.
The sample code is as follows:
import org.apache.ibatis.io.Resources;import org.apache.ibatis.jdbc.ScriptRunner;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Properties;/** * Run Sql script * sql script placed in the sql folder under resources*/public final class RunSqlScript { /** * <p>Run the specified sql script* @param sqlFileName The name of the sql script that needs to be executed*/ public static void run(String sqlFileName) { try { // Get database related configuration information Properties props = Resources.getResourceAsProperties("db.properties"); // jdbc connection information: Note: The current version of JDBC does not need to configure driver because Class.forName does not require manual loading of driver String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); // Establish a connection Connection conn = DriverManager.getConnection(url, username, password); // Create ScriptRunner to execute SQL script ScriptRunner runner = new ScriptRunner(conn); runner.setErrorLogWriter(null); runner.setLogWriter(null); // Execute SQL script runner.runScript(Resources.getResourceAsReader("sql/" + sqlFileName + ".sql")); // Close the connection conn.close(); // If successful, print the prompt message System.out.println("====== SUCCESS ========"); } catch (IOException | SQLException e) { e.printStackTrace(); } }} ps: In the current version of JDBC driver, there is no need to load driver and manual class.forName(driver) as before to load the driver. For details, you can click on DriverManager to see. There is a static {} static code block, which has loaded the initialized driver for us.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.