将 SELECT COUNT(*) 查询结果分配给 Java 变量
我在将 SELECT COUNT(*) 查询的结果分配给 Java 变量时遇到问题。我将查询结果分配给 ResultSet。然后,我尝试检索计数的值并将其分配给变量。我在尝试执行此操作时遇到错误。
这是我的代码:
ResultSet rc1 = null;
int rowCount1;
Statement stat = conn.createStatement();
rc1 = stat.executeQuery("SELECT COUNT(*) AS rowcount1
FROM Signal WHERE SignalId = 1;");
if (rc1.next())
rowCount1 = rc1.getInt("rowcount1");
然后我收到以下错误:
java.sql.SQLException:没有这样的列:'rowcount1'
在 org.sqlite.RS.findColumn(RS.java:116)
在 org.sqlite.RS.getInt(RS.java:219)
显然,问题在于尝试将 AS 之后的内容分配给变量时。我找不到很多关于包含 AS 的查询的信息。我在未计数的查询中遇到了同样的错误。例如,如果我有以下代码:
ResultSet rp1 = null;
int rowCount1 = 0;
Statement stat = conn.createStatement();
rp1 = stat.executeQuery("SELECT Signal AS Sig1
FROM Observations WHERE SignalId = 1;");
if (rp1.next())
rowCount1 = rp1.getInt("rowcount1");
我会得到与之前的代码相同的错误(没有这样的列:rowCount1)。我做错了什么?我确保我正在读取的表包含正确的值,因此查询必须为真。
I have been having problems assigning the result of a SELECT COUNT(*)
query to a Java variable. I am assigning the result of the query to a ResultSet. Then, I am trying to retrieve the value of the count and assigning it to a variable. I am getting an error when trying to do this.
Here is my code:
ResultSet rc1 = null;
int rowCount1;
Statement stat = conn.createStatement();
rc1 = stat.executeQuery("SELECT COUNT(*) AS rowcount1
FROM Signal WHERE SignalId = 1;");
if (rc1.next())
rowCount1 = rc1.getInt("rowcount1");
Then I get the following error:
java.sql.SQLException: no such column: 'rowcount1'
at org.sqlite.RS.findColumn(RS.java:116)
at org.sqlite.RS.getInt(RS.java:219)
Apparently, the problem is when trying to assign what goes after AS to a variable. I can't find a lot of information on queries containing AS. I get the same error with queries where I am not counting. For example if I have the following code:
ResultSet rp1 = null;
int rowCount1 = 0;
Statement stat = conn.createStatement();
rp1 = stat.executeQuery("SELECT Signal AS Sig1
FROM Observations WHERE SignalId = 1;");
if (rp1.next())
rowCount1 = rp1.getInt("rowcount1");
I get the same error with the previous code (no such column: rowCount1). What I am doing wrong? I am making sure the table I am reading contains the correct values so the query has to be true.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用 rp1.getInt(1) 即可——这会以 int 形式返回结果集中的第一列——这就是您想要的。
如果您有更多值,请使用 rp1.getInt(2) 来获取第二个值等...
Simply use
rp1.getInt(1)
-- this returns the first column from the resultset as an int -- which is what you want.If you have more values use
rp1.getInt(2)
to get the second value etc...第二个示例有一个错误:
将始终失败,因为查询中没有
rowcount1
列。The second example has an error:
will always fail because you have no
rowcount1
column in your query.