简体   繁体   中英

Java - Execute SQL queries only once

I'm developing a J2EE application with Spring framework and MySQL database. I want to execute the SQL script from java (probably with a request mapping) only once. I have store the sql statements in a properties file as a key-value pair and I loop through each key and execute the statement.

    Connection con = ds.getConnection();
    Statement stmt = con.createStatement();

    Enumeration enuKeys = properties.keys();
    while (enuKeys.hasMoreElements()) {
        String key = (String) enuKeys.nextElement();
        String value = properties.getProperty(key);
        stmt.execute(value);
    }

Is this the correct way of doing? or is there any other way doing the same? Thanks in advance.

Update:

As mentioned in the comment, I tried Spring jdbc intialize database but it is not executing all the queries in the sql file. Only the first 'create' query is executed successfully and it throws an execption "Table 'table_name' already exists". Other queries in the .sql file is not executed. This happens every time I run the server. Kindly help

By the sound of it you're trying to setup database schema when your code starts and one of the statement couldn't be run because the table already exist. You need to use statements that checks beforehand (eg: CREATE TABLE IF NOT EXISTS ) or catch the exception after executing each statement so it can proceed to the next one.

try {
  stmt.execute(value);
} catch (Exception e) {
  //.. raise some warning and continue ..
}

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