简体   繁体   中英

Using java to input SQL Query with backslash

I have a java program which connects to a database in Oracle SQL Developer. I need data from the database to export to a .csv file. I can do this directly in SQL Developer using spooling as shown

spool D:\fileLocation\fileName.csv
select /*csv*/ * from Table;
spool off

I need to be able to input that to SQL Developer FROM the java program. I can input a query from java to sql using code below

Statement SumLevel = connection.createStatement();
    try{
        SumLevel.executeQuery("SQL Query");
        System.out.println("Succesfuly Entered Data");

    }catch(SQLException e){
        System.out.println(e);
    }finally{
        if(CompareLevel != null){
            CompareLevel.close();
        }
    }

Obviously the \\ in java is not just a character so if I try the first line of the spooling in java it will try to do \\f which is a separate function.

Using \\\\ prints out the desired code but when it inputs into sql it says there is an error "java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement". I believe this is due to SQL reading the code showing \\\\ rather than \\

spool D:\\fileLocatoin\\fileName.csv
select /*csv*/ * from Table;
spool off

How would I be able to input the sql spooling code into a java program.

Thanks

Short answer You can't run spool command from Java .

Explanation.

Java is not connects to Oracle SQL Developer it connects to Oracle database. Oracle database can run SQL queries.

spool command is not part of SQL . It is command of Oracle SQL Developer command language.

Solution

Either you run your SQL query ( select * from Table , note that it doesn't allow comment in it) and then process result and write to file using some CSV lib.

Or you continue to use Oracle SQL Developer tool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM