仅执行第二个查询,执行第一个查询

时间:2014-06-11 12:59:11

标签: java mysql

我想在java中创建一个执行两个查询的函数,我想在其中执行此操作:

示例:

String s ="CREATE TABLE ClassRoom(ID int AUTO_INCREMENT PK ,
                              name char (2) not null,
                              section char (2) not null,
                              numberSt int not null,
                              )";
String s1 ="INSERT INTO ClassRoom VALUES (null,'5','A',25)";

pst = conn.prepareStatement(s);
               pst.executeUpdate();
               pst = conn.prepareStatement(s1);
               pst.executeUpdate();

我想在创建表时在表中放置一些值。 它第一次完美地工作,但第二次s没有被调用,因为有IF NOT EXISTS,但s1再次被调用。

我希望仅在s1已执行或已创建表时才调用s。如果该表已存在,我不想拨打s1查询。

3 个答案:

答案 0 :(得分:0)

根据您的SQL数据库,最简单的方法是使用upsert。如果数据不存在则会插入数据,否则会更新。您需要删除生成的密钥,并使用复合密钥从任何值中唯一标识房间。

答案 1 :(得分:0)

您可以使用以下查询检查表是否存在:

SELECT * 
FROM information_schema.tables
WHERE table_schema = 'yourdb' 
    AND table_name = 'ClassRoom'
LIMIT 1;

答案 2 :(得分:0)

您必须测试表是否已创建。

boolean existsTable = false;

//  use significative variable names... always!
String createQuery = 
            "CREATE TABLE ClassRoom( " +
                                   "ID       int  AUTO_INCREMENT PK, " +
                                   "name     char (2) not null, "      +
                                   "section  char (2) not null, "      +
                                   "numberSt int      not null, "      +
                                   ")";

String defaultValuesQuery ="INSERT INTO ClassRoom VALUES (null,'5','A',25)";

String checkTableQuery = "SELECT * "                       +
                     "FROM information_schema.tables " +
                     "WHERE table_schema = 'yourdb' "  +
                     "AND table_name = 'ClassRoom' "   +
                         "LIMIT 1;";

PreparedStatement pst = conn.prepareStatement(checkTableQuery);
ResultSet rs = pst.executeQuery();

// if the check query returns some value then table exists!
if (rs.next()) {
    existsTable = true;

// if table don't exists, create it 
} else {
    pst = conn.prepareStatement(createQuery);
    pst.executeUpdate();
}

// execute query only if table exists
if (existsTable) {
    pst = conn.prepareStatement(defaultValuesQuery);
    pst.executeUpdate();
}
相关问题