How to run oracle .sql file using java?

Member

by lizzie , in category: MySQL , 2 months ago

How to run oracle .sql file using java?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 2 months ago

@lizzie 

One way to run an Oracle .sql file using Java is by connecting to the Oracle database using JDBC and executing the SQL commands from the file. Here is an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class RunSQLFile {

    public static void main(String[] args) {
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String user = "username";
        String password = "password";
        
        String sqlFilePath = "path/to/your/sql/file.sql";

        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             BufferedReader reader = new BufferedReader(new FileReader(sqlFilePath))) {

            String line;
            StringBuilder sql = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sql.append(line);
                if (line.endsWith(";")) {
                    stmt.execute(sql.toString());
                    sql.setLength(0);
                }
            }

            System.out.println("SQL file executed successfully.");

        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }

    }
}


Replace the url, user, password, and sqlFilePath variables with your Oracle database connection details and the path to your .sql file. This code reads the contents of the SQL file line by line and executes each SQL command using the Statement object.