在java中设置准备并执行查询

时间:2014-05-13 05:56:15

标签: java mysql

我可以使用prepareStatement在java中一次执行以下查询吗?

SET @totalQuestion = (SELECT QuestionVolume FROM rules ORDER BY QuestionVolume DESC LIMIT 1);
PREPARE STMT FROM 'SELECT * FROM question ORDER BY RAND() LIMIT ?';
EXECUTE STMT USING @totalQuestion;

我正在考虑的Java代码??? (不确定我能做这样的事吗?)

generateQuestion = getDb().getConnection().prepareStatement(
                "SET @totalQuestion = (SELECT QuestionVolume FROM rules ORDER BY QuestionVolume DESC LIMIT 1);\n"
                + "\n"
                + "PREPARE STMT FROM 'SELECT * FROM question ORDER BY RAND() LIMIT ?';\n"
                + "EXECUTE STMT USING @totalQuestion;");

有人能解释一下在Java中执行查询的最佳原因吗?

更新

我将陈述改为以下内容。

 getQuestionRule = getDb().getConnection().prepareStatement(""
                + "SELECT QuestionVolume FROM rules ORDER BY QuestionVolume DESC LIMIT 1", Statement.RETURN_GENERATED_KEYS);
 generateQuestion = getDb().getConnection().prepareStatement(
                "SELECT * FROM question ORDER BY RAND() LIMIT ?", Statement.RETURN_GENERATED_KEYS);

2 个答案:

答案 0 :(得分:1)

使用Java变量来存储totalQuestion,使您的操作通过transactions进行原子化:

  1. 将JDBC自动提交设置为false:con = getDb().getConnection(); con.setAutoCommit(false);
  2. 执行第一个查询并将其结果加载到局部变量totalQuestion = result.getInt("QuestionVolume");
  3. 使用totalQuestion值执行第二个查询,而不是在mysql级别使用动态sql,而是在程序端编写sql:String sql = "SELECT * FROM question ORDER BY RAND() LIMIT ?"; PreparedStatement st = con.prepareStatement(sql); st.setInt(1,totalQuestion); ResultSet res = st.executeQuery();
  4. 将autocommit设置为true,从而提交您的交易:con.setAutoCommit(true)

答案 1 :(得分:1)

否:这些是两个语句,它们不能一次执行,除非它们在存储过程中分组。