SQL查询在PHPMyAdmin中有效,但在Java(JDBC)中无效

时间:2018-11-16 13:47:30

标签: java jdbc mariadb

我在Java中生成了以下字符串:

select * from `levelone_sessions` where user_session_key='-LIi-AlyYC37HfRezq7W' union select * from `changelang_sessions` where user_session_key='-LIi-AlyYC37HfRezq7W' union select * from `leveltwo_sessions` where user_session_key='-LIi-AlyYC37HfRezq7W' union select * from `levelthree_sessions` where user_session_key='-LIi-AlyYC37HfRezq7W' union select * from `sequence_sessions` where user_session_key='-LIi-AlyYC37HfRezq7W' union select * from `search_sessions` where user_session_key='-LIi-AlyYC37HfRezq7W' union select * from `settings_sessions` where user_session_key='-LIi-AlyYC37HfRezq7W'

,然后使用PreparedStatement将其转换为SQL语句。现在,此SQL查询在PHPMyAdmin中可以正常工作,并成功给出以下输出:

PHPMyAdmin output screenshot

但是,当从Java程序中执行同一查询时,它将引发以下异常:

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'where user_session_key='-LIi-AlyYC37HfRezq7W'' at line 1

不太确定为什么会这样。救命!

编辑:

这是实际上生成上述字符串并将其作为SQL语句执行的Java代码。

Collection<String> activities = Utilities.AppActivities.values();
int no_of_activities = activities.size(), i=0;
query = "";
for(String activity: activities) {
if(i < no_of_activities-1) {
    query += "select * from `" + activity + "` where user_session_key='" + session_key + "' union ";
}
else {
    query += "select * from `" + activity + "` where user_session_key='" + session_key + "'";
}
i++;
}
System.out.println(query);
stmt = con.prepareStatement(query);
rs = stmt.executeQuery();
duration = 0;
while(rs.next()) {
    duration += rs.getInt("duration");
}

0 个答案:

没有答案