Home >Database >Mysql Tutorial >How Can I Execute a MySQL .sql Script Using JDBC?
Streamlining MySQL Database Setup with JDBC and ScriptRunner
JDBC offers a powerful way to interact with MySQL databases. However, manually creating multiple tables using individual JDBC statements can be cumbersome. This article demonstrates a more efficient approach: executing entire .sql scripts directly via JDBC.
The Solution: Leveraging ScriptRunner
The key to efficient script execution is the ScriptRunner
class. This utility simplifies the process of running SQL scripts within your JDBC code. Here's how:
Establish a Database Connection: Obtain your JDBC Connection
object (conn
) using standard JDBC connection methods.
Instantiate ScriptRunner: Create a ScriptRunner
instance, specifying parameters for auto-commit behavior and error handling:
<code class="language-java">ScriptRunner runner = new ScriptRunner(conn, false, false); // false for both autoCommit and stopOnError</code>
Execute the Script: Use the runScript()
method to execute your .sql file:
<code class="language-java">runner.runScript(new BufferedReader(new FileReader("test.sql")));</code>
This concise code snippet executes all SQL commands within "test.sql". This method drastically reduces code complexity compared to manually executing each SQL statement. The ScriptRunner
handles the parsing and execution, streamlining your database setup process.
The above is the detailed content of How Can I Execute a MySQL .sql Script Using JDBC?. For more information, please follow other related articles on the PHP Chinese website!