{"id":120935,"date":"2023-11-10T17:37:00","date_gmt":"2023-11-10T15:37:00","guid":{"rendered":"https:\/\/examples.javacodegeeks.com\/?p=120935"},"modified":"2023-11-10T17:37:02","modified_gmt":"2023-11-10T15:37:02","slug":"running-a-sql-script-file-in-java","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/","title":{"rendered":"Running a SQL Script File in Java"},"content":{"rendered":"<p>In Java, we can interact with databases using various libraries and frameworks, but sometimes we may need to run SQL script files to perform tasks like schema creation, data population, or database migrations. Before we can execute SQL script files, we need to choose a Java database library that suits our needs. Some popular options include JDBC, Hibernate, JPA (Java Persistence API), <a href=\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/spring\/spring-jdbc-storedprocedure-class-example\/\" target=\"_blank\" rel=\"noreferrer noopener\">Spring JDBC<\/a>, or <a href=\"https:\/\/mybatis.org\/mybatis-3\/\" target=\"_blank\" rel=\"noreferrer noopener\">MyBatis<\/a>. For this article, we&#8217;ll explore how to run a SQL script file in Java using MyBatis, JDBC, and Spring JDBC.<\/p>\n<h2 class=\"wp-block-heading\">1. Setting Up the Database Environment<\/h2>\n<p>In this article, we will be using MySQL which is one of the most popular open-source relational database management systems, known for its reliability, performance, and scalability. To download MYSQL, go to the MySQL official website (<a href=\"https:\/\/www.mysql.com\/downloads\/\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.mysql.com\/downloads\/<\/a>) and select the MySQL Community Server edition that matches your operating system. <\/p>\n<p>On macOS, we can use the Homebrew package manager to install MySQL with the following commands: <\/p>\n<pre class=\"brush:bash\">\nbrew update\nbrew install mysql\n<\/pre>\n<p>After installation, we can start the MySQL server with:<\/p>\n<pre class=\"brush:bash\">\nbrew services start mysql\n<\/pre>\n<p>Once MySQL is installed, we need to open a terminal and use the following command to log in to MySQL using the root user:<\/p>\n<pre class=\"brush:bash\">\nmysql -u root -p\n<\/pre>\n<p>The above command will prompt us to enter the root password. Once we&#8217;ve logged in successfully, we are all set to begin using MySQL.<\/p>\n<h3 class=\"wp-block-heading\">1.1 What is a SQL (Database) Script File<\/h3>\n<p>A SQL (database) script file is a plain text file containing a sequence of structured queries and commands written in SQL (Structured Query Language). It is a document comprising numerous SQL queries distinctly separated. Typically, SQL script files have the file extension <code>.sql<\/code>. <\/p>\n<p>These scripts are used to define, manipulate, or interact with a database. The primary purposes of database script files include:<\/p>\n<ul class=\"wp-block-list\">\n<li><strong>Database Schema Definition<\/strong>: Creating tables, defining relationships, specifying constraints, and establishing the overall structure of a database.<\/li>\n<li><strong>Data Manipulation<\/strong>: Inserting, updating, or deleting data within the database. This can include seeding initial data or modifying existing records.<\/li>\n<li><strong>Database Migration<\/strong>: Managing changes to the database schema over time, especially when transitioning between different versions of an application.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\">1.2 Prepare the SQL Script File<\/h3>\n<p>Next, create an SQL script file named <code>students-script.sql<\/code> with the SQL statements we want to execute. In this article, <code>students-script.sql<\/code> file contains the following content:<\/p>\n<pre class=\"brush:sql\">\n\nCREATE TABLE IF NOT EXISTS studentDatabase.students (\n  id INT AUTO_INCREMENT PRIMARY KEY,\n  firstname VARCHAR(50) NOT NULL,\n  lastname VARCHAR(50) NOT NULL, \n  email VARCHAR(100) NOT NULL\n);\n\nINSERT INTO students (firstname, lastname, email) VALUES ('Thomas', 'P', 'charlesp@yahoo.com');\nINSERT INTO students (firstname, lastname, email) VALUES ('Charles', 'D', 'charlesd@gmail.com');\nINSERT INTO students (firstname, lastname, email) VALUES ('James', 'B', 'jamesb@yahoo.com');\nINSERT INTO students (firstname, lastname, email) VALUES ('Jonathan', 'S', 'jonathans@gmail.com');\nINSERT INTO students (firstname, lastname, email) VALUES ('John', 'Joe', 'john@example.com');\nINSERT INTO students (firstname, lastname, email) VALUES ('Jane', 'Doe', 'jane@example.com');\n\n\n<\/pre>\n<p>The above file will create a <code>table<\/code> named <code>students<\/code> in a MySQL database called <code>studentDatabase<\/code> and populate it with two records.<\/p>\n<h2 class=\"wp-block-heading\">2. Running a SQL Script File using MyBatis ScriptRunner<\/h2>\n<h3 class=\"wp-block-heading\">2.1 What is MyBatis<\/h3>\n<p>MyBatis is a popular Java-based persistence framework that provides a simple and efficient way for Java applications to interact with relational databases, and one of its powerful features is the ScriptRunner. MyBatis allows developers to map Java objects to SQL statements using XML or annotations. It supports a variety of database operations, including simple queries, complex joins, and stored procedures.<\/p>\n<h3 class=\"wp-block-heading\">2.2 What is MyBatis ScriptRunner<\/h3>\n<p>MyBatis <a href=\"https:\/\/github.com\/mybatis\/mybatis-3\/blob\/master\/src\/main\/java\/org\/apache\/ibatis\/jdbc\/ScriptRunner.java\">ScriptRunner<\/a> simplifies the process of running multiple SQL statements and scripts by providing an API for reading SQL files and carrying out their execution on a preconfigured database connection.<\/p>\n<p>By leveraging MyBatis ScriptRunner, we have the capability to automate tasks such as setting up database schemas, populating our database with initial data, and executing various database maintenance operations, eliminating the necessity to manually execute individual SQL statements one after another.<\/p>\n<h3 class=\"wp-block-heading\">2.3 Set Up MyBatis in Your Java Project<\/h3>\n<p>To execute an SQL script using MyBatis ScriptRunner, we need to have MyBatis set up in our Java project, a pre-configured database connection, and the SQL script file that we want to run. To integrate MyBatis into our Java Maven project, add the MyBatis and the MySQL JDBC driver dependencies in our <code>pom.xml<\/code> file like this:<\/p>\n<pre class=\"brush:xml\">\n    &lt;dependencies&gt;       \n        &lt;!-- Add MyBatis Dependencies --&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.mybatis&lt;\/groupId&gt;\n            &lt;artifactId&gt;mybatis&lt;\/artifactId&gt;\n            &lt;version&gt;3.5.6&lt;\/version&gt; \n        &lt;\/dependency&gt;\n    \n        &lt;!-- Add MySQL JDBC Driver --&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;mysql&lt;\/groupId&gt;\n            &lt;artifactId&gt;mysql-connector-java&lt;\/artifactId&gt;\n            &lt;version&gt;8.0.26&lt;\/version&gt; &lt;!-- Use the version that matches your MySQL server --&gt;\n        &lt;\/dependency&gt;\n    &lt;\/dependencies&gt;\n<\/pre>\n<h3 class=\"wp-block-heading\">2.4 Configure MyBatis and ScriptRunner<\/h3>\n<p>Now, in our Java code, we need to configure MyBatis and the ScriptRunner to execute the SQL script file. We also need to create a new directory&nbsp;<code>src\/main\/resources<\/code>&nbsp;and place the <code>students-script.sql<\/code> file there. The updated code should look like the code sample shown below:<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<pre class=\"brush:java\">\npublic class ExecuteSQLScriptWithMyBatis {\n\n    public static void main(String[] args) throws Exception {\n\n        \/\/Register the Driver\n        Class.forName(\"com.mysql.cj.jdbc.Driver\");\n\n        \/\/ Establish a MySQL database connection\n        String jdbcUrl = \"jdbc:mysql:\/\/localhost:3306\/studentDatabase\";\n        String username = \"your_username\";\n        String password = \"your_password\";\n        Connection connection = DriverManager.getConnection(jdbcUrl, username, password);\n        System.out.println(\"Connection Established......\");\n\n        \/\/ Create a ScriptRunner instance\n        ScriptRunner scriptRunner = new ScriptRunner(connection);\n\n        \/\/ Set the delimiter to define the end of a statement (default is ';')\n        scriptRunner.setDelimiter(\";\");\n\n        \/\/ Read and execute the SQL script\n        Reader scriptReader = Resources.getResourceAsReader(\"students-script.sql\");\n        scriptRunner.runScript(scriptReader);\n\n        \/\/ Close the resources\n        scriptReader.close();\n        connection.close();\n\n    }\n}\n\n<\/pre>\n<p>In the code above, We start by establishing a MySQL database connection by providing the appropriate database <code>URL<\/code>, <code>username<\/code>, and <code>password<\/code>. Note that you need to replace <code>\"jdbc:mysql:\/\/localhost:3306\/studentdatabase\"<\/code>, <code>\"your_username\"<\/code>, and <code>\"your_password\"<\/code> with your actual database URL, username, and password.<\/p>\n<p>Next, we create an <code>ScriptRunner<\/code> instance and then set the delimiter (usually <code>;<\/code>). Next, we create an <code>Reader<\/code> object named <code>scriptReader<\/code> to read the content of the <code>students-script.sql<\/code> script file. We then read and execute the SQL script using <code>scriptRunner.runScript(scriptReader)<\/code>.<\/p>\n<p>Finally, we close the resources to release the database connection. If we compile and run our Java application, It will execute the <code>students-script.sql<\/code> file against our configured MySQL <code>studentDatabase<\/code> , and the output on Netbeans IDE and MySQL workbench is shown in Fig 1 and Fig 2 respectively.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><a href=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/scriptrunner_netbeans.png\"><img decoding=\"async\" width=\"885\" height=\"375\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/scriptrunner_netbeans.png\" alt=\"Fig 1: Output from Running a SQL Script File using MyBatis ScriptRunner\" class=\"wp-image-120996\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/scriptrunner_netbeans.png 885w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/scriptrunner_netbeans-300x127.png 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/scriptrunner_netbeans-768x325.png 768w\" sizes=\"(max-width: 885px) 100vw, 885px\" \/><\/a><figcaption class=\"wp-element-caption\">Fig 1: Output from Running a SQL Script File using MyBatis ScriptRunner<\/figcaption><\/figure>\n<\/div>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><a href=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/mysqlworkbench.png\"><img decoding=\"async\" width=\"1024\" height=\"548\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/mysqlworkbench-1024x548.png\" alt=\"\" class=\"wp-image-120997\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/mysqlworkbench-1024x548.png 1024w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/mysqlworkbench-300x161.png 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/mysqlworkbench-768x411.png 768w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/mysqlworkbench.png 1070w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">Fig 2: Student Table created on MySQL Workbench<\/figcaption><\/figure>\n<\/div>\n<h2 class=\"wp-block-heading\">3. Running SQL Statements in Batches from a Script File using JDBC <\/h2>\n<p>JDBC is a Java-based API that allows Java applications to interact with relational databases providing an interface for connecting to databases and executing SQL queries. <\/p>\n<p>When dealing with multiple operations, executing SQL statements one by one can be inefficient. JDBC provides a mechanism for executing SQL statements in batches, which can significantly improve performance.<\/p>\n<p>The code listing below shows how to execute SQL statements in batches from an SQL script file in a Java application:<\/p>\n<pre class=\"brush:java\">\npublic class ExecuteSQLScriptJDBC {\n\n    public static void main(String[] args) throws Exception {\n\n        \/\/Register the Driver\n        Class.forName(\"com.mysql.cj.jdbc.Driver\");\n\n        \/\/ Establish a MySQL database connection\n        String jdbcUrl = \"jdbc:mysql:\/\/localhost:3306\/studentDatabase\";\n        String username = \"username\";\n        String password = \"password\";\n        try {\n            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);\n\n            \/\/ Define the path to the SQL script file\n            \/\/ Update the path as needed\n            String script = readSQLScript(\"\/Users\/omozegieaziegbe\/Development\/students-script.sql\");\n            executeScript(connection, script);\n\n            \/\/Close the connection\n            connection.close();\n\n            \/\/Handle Exceptions\n        } catch (SQLException | IOException e) {\n            e.printStackTrace();\n        }\n\n    }\n\n    \/\/ Read the SQL Script File\n    public static String readSQLScript(String filePath) throws IOException {\n        StringBuilder script = new StringBuilder();\n        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {\n            String line;\n            while ((line = reader.readLine()) != null) {\n                script.append(line).append(\"\\n\");\n            }\n        }\n        return script.toString();\n    }\n\n    \/\/Execute the SQL Script File\n    public static void executeScript(Connection connection, String script) throws SQLException {\n        try (Statement statement = connection.createStatement()) {\n            String[] sqlCommands = script.split(\";\");\n            for (String sqlCommand : sqlCommands) {\n                if (!sqlCommand.trim().isEmpty()) {\n                    statement.addBatch(sqlCommand);\n                }\n            }\n            statement.executeBatch();\n        }\n    }\n\n}\n\n\n<\/pre>\n<p>In the above code listings, we start by establishing a connection to the database. We use the <code>DriverManager<\/code> class to create a connection object by providing the database <code>URL, username, and password<\/code>. Replace <code>\"jdbc:mysql:\/\/localhost:3306\/studentdatabase\"<\/code>, <code>\"username\"<\/code>, and <code>\"password\"<\/code> with your actual database URL, username, and password.<\/p>\n<p>Next, we create a method named <code>readSQLScript<\/code> which we use to read the SQL statements from a script file (<code>students-script.sql<\/code>). To accomplish this, we use the <code>BufferedReader<\/code> class to read the script file from our file system. Note that this script file contains multiple SQL statements, separated by semicolons (<code>;<\/code>). We then split the script content into individual SQL commands using the semicolon as a delimiter using the string <code>split(\";\")<\/code> method storing the result of this operation in an <code>String[]<\/code> array variable declared as<code> sqlCommands<\/code>.<\/p>\n<p>Next, we Iterate through the array of SQL statements and add them to the batch using the <code>addBatch<\/code> method. After adding all the statements to the batch, we execute them using the <code>executeBatch<\/code> method. Finally, In our main method, we call the <code>executeScript(connection, script)<\/code> method passing the established database connection (<code>connection<\/code>) and the script (<code>script<\/code>) to execute the SQL script on the database.<\/p>\n<p>It&#8217;s important to note that for this code example to run successfully, we must ensure that our script file does not contain <strong>comments<\/strong> or lines starting with <strong>&#8220;&#8211;&#8220;<\/strong>, <strong>&#8220;\/*&#8221;<\/strong>, or any other non-alphabetic characters.<\/p>\n<h3 class=\"wp-block-heading\">3.1 Handling Exceptions<\/h3>\n<p>When working with databases, it is recommended to always handle exceptions properly. In the example above, we use the <code>catch (SQLException | IOException e)<\/code> method to handle any exception of type <code>SQLException<\/code> or <code>IOException<\/code> within our <code>try<\/code> block and If any exception of type <code>SQLException<\/code> or <code>IOException<\/code> is thrown, the code inside the <code>catch<\/code> block will be executed.<\/p>\n<h3 class=\"wp-block-heading\">3.2 Closing the Connection<\/h3>\n<p>We make sure to properly close the database connection once we have completed our tasks in order to free up valuable resources. In this example, the <code>close()<\/code> method is called on the <code>Connection<\/code> object in a <code>try<\/code> block for proper resource cleanup.<\/p>\n<h2 class=\"wp-block-heading\">4. Running a SQL Script File using Spring JDBC<\/h2>\n<p>Spring JDBC <code><a href=\"https:\/\/docs.spring.io\/spring-framework\/docs\/current\/javadoc-api\/org\/springframework\/jdbc\/datasource\/init\/ScriptUtils.html\">ScriptUtils<\/a><\/code> is a convenient tool for executing SQL scripts in Java applications. The <code>ScriptUtils<\/code> class provides utility methods for handling SQL scripts when used alongside JDBC. <\/p>\n<p>Listed below are some of the methods provided by the <code>ScriptUtils<\/code> class to execute a script file:<\/p>\n<ul class=\"wp-block-list\">\n<li><code>executeSqlScript(Connection connection, Resource resource)<\/code><\/li>\n<li><code>executeSqlScript(Connection connection, EncodedResource resource)<\/code><\/li>\n<li><code>executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError, boolean ignoreFailedDrops, String[] commentPrefixes, String separator, String blockCommentStartDelimiter, String blockCommentEndDelimiter)<\/code><\/li>\n<li><code>executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError, boolean ignoreFailedDrops, String commentPrefix, String separator, String blockCommentStartDelimiter, String blockCommentEndDelimiter)<\/code><\/li>\n<\/ul>\n<p>To execute SQL scripts using Spring JDBC <code>ScriptUtils<\/code> in Java, create a Java Maven application and add the Spring JDBC, Spring Core, and MySQL JDBC driver dependencies to the pom.xml file in the project like this:<\/p>\n<pre class=\"brush:xml\">\n    &lt;dependencies&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-jdbc&lt;\/artifactId&gt;\n            &lt;version&gt;5.3.14&lt;\/version&gt; &lt;!-- Replace with your Spring version --&gt;\n        &lt;\/dependency&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-core&lt;\/artifactId&gt;\n            &lt;version&gt;5.3.14&lt;\/version&gt; &lt;!-- Replace with your Spring version --&gt;\n        &lt;\/dependency&gt;\n        &lt;!-- Add MySQL JDBC Driver --&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;mysql&lt;\/groupId&gt;\n            &lt;artifactId&gt;mysql-connector-java&lt;\/artifactId&gt;\n            &lt;version&gt;8.0.26&lt;\/version&gt; &lt;!-- Use the version that matches your MySQL server --&gt;\n        &lt;\/dependency&gt;\n    &lt;\/dependencies&gt; \n<\/pre>\n<p>Next, create or copy the SQL script file <code>students-script.sql<\/code> to a directory where you want to load the file and update the Java class to execute the SQL script. Note that the directory should be accessible by the application. <\/p>\n<p>Below is the updated Java class:<\/p>\n<pre class=\"brush:java\">\n\npublic class ExecuteSQLScriptSpringJDBC {\n\n    public static void main(String[] args) throws Exception {\n        \n        \/\/Database URL\n        String url = \"jdbc:mysql:\/\/localhost:3306\/studentDatabase\";\n\n        \/\/Register the Driver\n        Class.forName(\"com.mysql.cj.jdbc.Driver\");\n        \n        \/\/ Establish a MySQL database connection\n        String username = \"root\";\n        String password = \"omozegie\";\n        Connection connection = DriverManager.getConnection(url, username, password);\n        \n        System.out.println(\"Establishing Connection.....\");\n        \n        \/\/ Define the path to the SQL script file\n        \/\/ Update the path as needed\n        File file = new File(\"\/Users\/omozegieaziegbe\/Development\/students-script.sql\");\n        Resource resource = new FileSystemResource(file);\n        EncodedResource encodedresource = new EncodedResource(resource);\n        \n        connection.setAutoCommit(false);\n        \n        \/\/ Execute the SQL script\n        ScriptUtils.executeSqlScript(connection, encodedresource);\n        connection.setAutoCommit(true);\n\n        connection.close();\n\n        System.out.println(\"Database Tables Created\");\n    }\n}\n\n<\/pre>\n<p>In the example above, the script file is loaded using <code>File<\/code> instead of a classpath resource. Replace the paths and file names with the appropriate values in your application. <\/p>\n<p>We create a <code>Resource<\/code> object named <code>resource<\/code> which is used to read the SQL script file on our filesystem and create an <code>EncodedResource<\/code> object named <code>encodedresource<\/code> by passing the <code>resource<\/code> as an argument to its constructor. In Spring Framework, <code>EncodedResource<\/code> is a utility class used for reading resources with specified character encodings such as those in an SQL script file.<\/p>\n<p>Finally, we use the <code>ScriptUtils.executeSqlScript(connection, encodedresource)<\/code> method to execute the SQL script. This method accepts two parameters &#8211; <code>Connection connection<\/code> which is the JDBC connection already configured and <code>EncodedResource resource<\/code> which is the resource to load the SQL script. This method generally takes care of opening a connection and executing the script.<\/p>\n<p>When we run this Java application, it will execute the SQL script <code>students-script<\/code>, creating the <code>students<\/code> table and insert the specified records in the students&#8217; database.<\/p>\n<h2 class=\"wp-block-heading\">5. Conclusion<\/h2>\n<p>In this article, We have shown various code examples on how to execute SQL script files using JDBC, MyBatis, and Spring ScriptUtils library. Running an SQL script file in a Java application provides a flexible mechanism for interacting with databases. Whether you are initializing a database, performing data migration, or creating database tables, Java&#8217;s capabilities in conjunction with database libraries like Spring JDBC, and MyBatis, or using JDBC to execute SQL statements in batches make it a straightforward process.<\/p>\n<p>By employing libraries such as Spring&#8217;s <code>ScriptUtils<\/code> or MyBatis <code>ScriptRunner<\/code>, we can efficiently execute SQL script files, ensuring that our application&#8217;s database interactions are well-structured. This approach allows for better management of database schema changes, minimizes the risk of errors, and provides an organized way to handle database-related operations.<\/p>\n<p>Overall, running SQL script files in Java enables us to manage our database operations seamlessly, ultimately contributing to the robustness of our applications.<\/p>\n<h2 class=\"wp-block-heading\">6. Download the Source Code<\/h2>\n<p>This was an example of how to run an SQL Script File in Java.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/11\/runSQLScriptFileJava.zip\"><strong>Running a SQL Script File in Java<\/strong><\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>In Java, we can interact with databases using various libraries and frameworks, but sometimes we may need to run SQL script files to perform tasks like schema creation, data population, or database migrations. Before we can execute SQL script files, we need to choose a Java database library that suits our needs. Some popular options &hellip;<\/p>\n","protected":false},"author":252,"featured_media":94233,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[881,1055,47044,47045],"class_list":["post-120935","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-core-java","tag-database","tag-sql","tag-sql-script-execution","tag-sql-script-runner"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Running a SQL Script File in Java - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"Learn how to execute SQL script files in Java. Discover methods to run SQL scripts for your database tasks in Java programming.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Running a SQL Script File in Java - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"Learn how to execute SQL script files in Java. Discover methods to run SQL scripts for your database tasks in Java programming.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:author\" content=\"https:\/\/web.facebook.com\/omos.aziegbe\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-10T15:37:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-10T15:37:02+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/09\/java-logo.png\" \/>\n\t<meta property=\"og:image:width\" content=\"225\" \/>\n\t<meta property=\"og:image:height\" content=\"225\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Omozegie Aziegbe\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/OAziegbe\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Omozegie Aziegbe\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/\"},\"author\":{\"name\":\"Omozegie Aziegbe\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/53e9141bb43ca17cd84b5ab586ca5199\"},\"headline\":\"Running a SQL Script File in Java\",\"datePublished\":\"2023-11-10T15:37:00+00:00\",\"dateModified\":\"2023-11-10T15:37:02+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/\"},\"wordCount\":1637,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/09\/java-logo.png\",\"keywords\":[\"database\",\"sql\",\"SQL Script Execution\",\"SQL Script Runner\"],\"articleSection\":[\"Core Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/\",\"name\":\"Running a SQL Script File in Java - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/09\/java-logo.png\",\"datePublished\":\"2023-11-10T15:37:00+00:00\",\"dateModified\":\"2023-11-10T15:37:02+00:00\",\"description\":\"Learn how to execute SQL script files in Java. Discover methods to run SQL scripts for your database tasks in Java programming.\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/09\/java-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/09\/java-logo.png\",\"width\":225,\"height\":225,\"caption\":\"anonymous class in java\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Development\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Core Java\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Running a SQL Script File in Java\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/53e9141bb43ca17cd84b5ab586ca5199\",\"name\":\"Omozegie Aziegbe\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/05\/cropped-jcg_profile_pic-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/05\/cropped-jcg_profile_pic-96x96.jpg\",\"caption\":\"Omozegie Aziegbe\"},\"description\":\"Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web\/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.\",\"sameAs\":[\"https:\/\/web.facebook.com\/omos.aziegbe\",\"https:\/\/www.linkedin.com\/in\/omosaziegbe\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/OAziegbe\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/omozegie-aziegbe\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Running a SQL Script File in Java - Java Code Geeks","description":"Learn how to execute SQL script files in Java. Discover methods to run SQL scripts for your database tasks in Java programming.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Running a SQL Script File in Java - Java Code Geeks","og_description":"Learn how to execute SQL script files in Java. Discover methods to run SQL scripts for your database tasks in Java programming.","og_url":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_author":"https:\/\/web.facebook.com\/omos.aziegbe","article_published_time":"2023-11-10T15:37:00+00:00","article_modified_time":"2023-11-10T15:37:02+00:00","og_image":[{"width":225,"height":225,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/09\/java-logo.png","type":"image\/png"}],"author":"Omozegie Aziegbe","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/OAziegbe","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Omozegie Aziegbe","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/"},"author":{"name":"Omozegie Aziegbe","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/53e9141bb43ca17cd84b5ab586ca5199"},"headline":"Running a SQL Script File in Java","datePublished":"2023-11-10T15:37:00+00:00","dateModified":"2023-11-10T15:37:02+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/"},"wordCount":1637,"commentCount":0,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/09\/java-logo.png","keywords":["database","sql","SQL Script Execution","SQL Script Runner"],"articleSection":["Core Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/","url":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/","name":"Running a SQL Script File in Java - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/09\/java-logo.png","datePublished":"2023-11-10T15:37:00+00:00","dateModified":"2023-11-10T15:37:02+00:00","description":"Learn how to execute SQL script files in Java. Discover methods to run SQL scripts for your database tasks in Java programming.","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/09\/java-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/09\/java-logo.png","width":225,"height":225,"caption":"anonymous class in java"},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/running-a-sql-script-file-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"},{"@type":"ListItem","position":4,"name":"Running a SQL Script File in Java"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/53e9141bb43ca17cd84b5ab586ca5199","name":"Omozegie Aziegbe","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/05\/cropped-jcg_profile_pic-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/05\/cropped-jcg_profile_pic-96x96.jpg","caption":"Omozegie Aziegbe"},"description":"Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web\/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.","sameAs":["https:\/\/web.facebook.com\/omos.aziegbe","https:\/\/www.linkedin.com\/in\/omosaziegbe\/","https:\/\/x.com\/https:\/\/twitter.com\/OAziegbe"],"url":"https:\/\/examples.javacodegeeks.com\/author\/omozegie-aziegbe\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/120935","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/252"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=120935"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/120935\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/94233"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=120935"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=120935"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=120935"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}