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

Java 执行第二个查询仅执行第一个查询,java,mysql,Java,Mysql,我想在java中创建一个函数,执行两个查询,我想在其中执行以下操作: 例如: String s ="CREATE TABLE ClassRoom(ID int AUTO_INCREMENT PK , name char (2) not null, section char (2) not null, numberSt

我想在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
时,如果不存在,则不会按原样调用,但另一次会再次调用
s1


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

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

您可以通过以下查询检查表是否存在:

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

您必须测试表是否已创建

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();
}

对不起,你能举个例子吗。。我从未使用过upsert,因此不知道如何使用。thnx;)我会尽力去理解它;)不管怎样,只要从createtable查询中删除IF-NOT-EXISTS,我就可以解决这个问题。如果该表已经存在,它将直接跳转到超出第二个查询的异常:D