Java程序中如何访问SQL count()查询的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2763659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you access the value of an SQL count () query in a Java program
提问by Ankur
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”,我不确定这是否会起作用,我认为不会。
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count");
while(rs3.next()){
count = rs3.getInt("count");
}
采纳答案by Bozho
Use aliases:
使用别名:
SELECT COUNT(*) AS total FROM ..
and then
进而
rs3.getInt("total")
回答by brabster
I would expect this query to work with your program:
我希望这个查询能与您的程序一起使用:
"SELECT COUNT(*) AS count FROM "+lastTempTable+")"
"SELECT COUNT(*) AS count FROM "+lastTempTable+")"
(You need to alias the column, not the table)
(您需要为列而不是表设置别名)
回答by Eric Eijkelenboom
回答by andrew
I have done it this way (example):
我是这样做的(示例):
String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"[email protected]"'";
int count=0;
try {
ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
while(rs.next())
count=rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//...
}
回答by geek
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
回答by Dhruv Pal
It's similar to above but you can try like
它与上面类似,但你可以尝试像
public Integer count(String tableName) throws CrateException {
String query = String.format("Select count(*) as size from %s", tableName);
try (Statement s = connection.createStatement()) {
try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
Preconditions.checkArgument(resultSet.next(), "Result set is empty");
return resultSet.getInt("size");
}
} catch (SQLException e) {
throw new CrateException(e);
}
}
}
回答by BalajiShanmugam
<%
try{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
if(con == null) System.out.print("not connected");
Statement st = con.createStatement();
String myStatement = "select count(*) as total from locations";
ResultSet rs = st.executeQuery(myStatement);
int num = 0;
while(rs.next()){
num = (rs.getInt(1));
}
}
catch(Exception e){
System.out.println(e);
}
%>