Reputation: 2100
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
Upvotes: 1
Views: 1548
Reputation: 41123
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 ..
}
Upvotes: 1