简体   繁体   English

Java-仅执行一次SQL查询

[英]Java - Execute SQL queries only once

I'm developing a J2EE application with Spring framework and MySQL database. 我正在使用Spring框架和MySQL数据库开发J2EE应用程序。 I want to execute the SQL script from java (probably with a request mapping) only once. 我只想从Java执行一次SQL脚本(可能带有请求映射)。 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. 我已将sql语句作为键值对存储在属性文件中,并且遍历每个键并执行该语句。

    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. 如评论中所述,我尝试了Spring jdbc初始化数据库,但是它没有执行sql文件中的所有查询。 Only the first 'create' query is executed successfully and it throws an execption "Table 'table_name' already exists". 只有第一个“创建”查询成功执行,并且抛出“表'table_name'已经存在”的执行。 Other queries in the .sql file is not executed. .sql文件中的其他查询未执行。 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. 您需要使用预先检查的语句(例如: CREATE TABLE IF NOT EXISTS ),或者在执行每个语句后捕获异常,以便可以继续执行下一个语句。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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