我可以使用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);
答案 0 :(得分:1)
使用Java变量来存储totalQuestion
,使您的操作通过transactions进行原子化:
con = getDb().getConnection();
con.setAutoCommit(false);
totalQuestion = result.getInt("QuestionVolume");
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();
con.setAutoCommit(true)
。答案 1 :(得分:1)
否:这些是两个语句,它们不能一次执行,除非它们在存储过程中分组。