如何访问Java程序中的SQL count()查询的值

时间:2021-10-19 13:35:39

I want to get to the value I am finding using the COUNT command of SQL. Normally I enter the column name I want to access into the getInt() getString() method, what do I do in this case when there is no specific column name.

我想使用SQL的COUNT命令获取我正在查找的值。通常,我输入要访问getInt() getString()方法的列名,当没有特定的列名时,我要做什么呢?

I have used 'AS' in the same manner as is used to alias a table, I am not sure if this is going to work, I would think not.

我使用“AS”的方式和使用“AS”作为表的别名是一样的,我不确定这是否可行,我认为不会。

Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count");
    while(rs3.next()){
    count = rs3.getInt("count");
    }

5 个解决方案

#1


74  

Use aliases:

使用别名:

SELECT COUNT(*) AS total FROM ..

and then

然后

rs3.getInt("total")

#2


40  

The answers provided by Bohzo and Brabster will obviously work, but you could also just use:

Bohzo和Brabster提供的答案显然是有效的,但是你也可以使用:

rs3.getInt(1);

to get the value in the first, and in your case, only column.

要在第一列中获取值,在本例中,只获取列。

#3


4  

I would expect this query to work with your program:

我希望这个查询可以与您的程序一起工作:

"SELECT COUNT(*) AS count FROM "+lastTempTable+")"

"从"+lastTempTable+"选择COUNT(*)作为COUNT "

(You need to alias the column, not the table)

(需要对列进行别名,而不是表)

#4


2  

I have done it this way (example):

我是这样做的(例子):

String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"r@r.com"'";
int count=0;
try {
    ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
    while(rs.next())
        count=rs.getInt(1);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //...
}

#5


1  

Statement stmt3 = con.createStatement();

ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");

count = rs3.getInt("count");

#1


74  

Use aliases:

使用别名:

SELECT COUNT(*) AS total FROM ..

and then

然后

rs3.getInt("total")

#2


40  

The answers provided by Bohzo and Brabster will obviously work, but you could also just use:

Bohzo和Brabster提供的答案显然是有效的,但是你也可以使用:

rs3.getInt(1);

to get the value in the first, and in your case, only column.

要在第一列中获取值,在本例中,只获取列。

#3


4  

I would expect this query to work with your program:

我希望这个查询可以与您的程序一起工作:

"SELECT COUNT(*) AS count FROM "+lastTempTable+")"

"从"+lastTempTable+"选择COUNT(*)作为COUNT "

(You need to alias the column, not the table)

(需要对列进行别名,而不是表)

#4


2  

I have done it this way (example):

我是这样做的(例子):

String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"r@r.com"'";
int count=0;
try {
    ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
    while(rs.next())
        count=rs.getInt(1);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //...
}

#5


1  

Statement stmt3 = con.createStatement();

ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");

count = rs3.getInt("count");