下面我展示了我在Java中动态的SQL查询。
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -365);
调整到当月之前的12个月,0小时和分钟
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1, 0, 0, 0);
String lastYearTime = String.valueOf(cal.getTimeInMillis() / 1000);
while(iterator.hasNext())
{
tablename = Database.getTableName((String)iterator.next());
fields = "status,count(*) as count";
query.append("select " + fields + " from " + tablename + " where");
query.append(" toid ='" + collegeId + "'");
query.append(" and dtstamp >='" + lastYearTime + "'");
query.append(" group by status");
if(i.hasNext())
query.append(" UNION ");
}
StringBuffer countquery = new StringBuffer("select status, SUM(count) as count from ( " + query + ")as temp group by status ");
ResultSet rs = Database.executeQuery(countquery.toString(), connection);
在上面的查询中,tablename将根据其他因素随机显示。 collegeId可以是任何id。状态可以是辍学,追求或任何随机状态。
当我执行上面的查询时,结果集工作正常并显示数据。但是当数据库中没有记录时,它会抛出一个sql语法错误1064,说明
您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以获得正确的语法,以便在状态')附近使用临时组。在第1行
答案 0 :(得分:1)
<强>问题1 强>
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')as temp group by status' at line 1
您的查询中存在问题:
select status, SUM(count) as count from ( " + query + ")as temp group by status
您应该在查询中留出空格:
from ( " + query + ")as
将此")as
替换为此") as
修改强>
<强> Problem2 强>
SQL Exception : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') as temp group by status' at line 1 SQL State : 42000 Error Code : 1064
您的查询为String
,因此您应将其置于两个'query'
现在替换它:
select status, SUM(count) as count from ( " + query + ")as temp group by status
由此:
select status, SUM(count) as count from ( '" + query + "') as temp group by status
祝你好运。
答案 1 :(得分:0)
当数据库中没有记录时,Resultset会引发语法错误
不,不。当您的查询中出现语法错误时,它会抛出语法错误异常。