Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javamysql执行更新_Java_Mysql - Fatal编程技术网

javamysql执行更新

javamysql执行更新,java,mysql,Java,Mysql,所以我有一个在数据库中查找外键的方法。如果外键不存在,它将向数据库中添加一个条目。现在,我在插入新记录之后要做的是再次查询以获取外键。这是过度杀伤力还是正确的做法?谢谢 private String getTestType(TestResult testResult) { String testTypeId = ""; String query = String.format("SELECT id FROM test_types WHERE " + "n

所以我有一个在数据库中查找外键的方法。如果外键不存在,它将向数据库中添加一个条目。现在,我在插入新记录之后要做的是再次查询以获取外键。这是过度杀伤力还是正确的做法?谢谢

private String getTestType(TestResult testResult) {
    String testTypeId = "";

    String query = String.format("SELECT id FROM test_types WHERE " +
            "name='%s'", testResult.getTestType());

    try {
        st = con.prepareStatement(query);
        rs = st.executeQuery();

        if (rs.next()) {
            testTypeId = rs.getString("id");
        } else {
            st = con.prepareStatement("INSERT INTO test_types (name, " +
                    "created_at) VALUES (?, ?)");
            st.setString(1, testResult.getTestType());
            st.setTimestamp(2, new java.sql.Timestamp(System
                    .currentTimeMillis()));

            st.executeUpdate();



            st = con.prepareStatement(query);
            rs = st.executeQuery();

            if (rs.next()) {
                testTypeId = rs.getString("id");
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
        System.out.println("There was an issue getting and or creating " +
                "test Type");
    }

    return testTypeId;
}

由于要在数据库中插入新行,因此必须执行查询以获取自动增量字段(id)。目前他们的做法是可行的。但在查询中几乎没有其他选择:

使用以下方法获取id:

另一种方法是在表的id列上执行
MAX

我相信在where子句中进行字符串比较时,这些查询将比查询快得多

rs = st.executeQuery("select last_insert_id() as last_id");
id= rs.getString("last_id");