我在JDBC中使用MySQL。
有没有办法在JDBC中使用类似“set@rank=0;”的user-defined variables?
具体来说,我想用JDBC实现排名。
set @rank = 0;
set @userCount = (select COUNT(*) from usertwo);
update usertwo A set userRank = 100*(@rank:=@rank+1/@userCount) order by (select AVG(B.votePoint) from votelist B where A.userNum = B.targetUserNum);
最佳答案
我是一个MySQL DBA,但我对JDBC一无所知(除了“它与Java有关”,这足以让我觉得阅读JDBC很痛苦)。。。不过,看来executeUpdate()
才是你要找的。
int executeUpdate(String sql)
throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE
statement or an SQL statement that returns nothing, such as an SQL DDL statement.
最后一部分(“不返回任何内容的SQL语句”)听起来像是对
SET @rank = 0
的恰当描述;对于结果集,它不返回任何内容。Parameters:
sql - an SQL Data Manipulation Language (DML) statement, such as INSERT,
UPDATE or DELETE; or an SQL statement that returns nothing,
such as a DDL statement.
Returns:
either (1) the row count for SQL Data Manipulation Language (DML)
statements or (2) 0 for SQL statements that return nothing
Throws:
SQLException - if a database access error occurs, this method is called on
a closed Statement or the given SQL statement produces a ResultSet object
http://docs.oracle.com/javase/6/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29
我想这和您在
UPDATE usertwo...
查询中使用的是一样的。。。因此,对同一数据库连接按顺序执行的三个executeUpdate()调用应该可以实现您的目的。或者,实际上,您只需要对数据库进行两次调用,因为前两次调用可以组合在一个查询中:
SET @rank = 0, @userCount = (select COUNT(*) from usertwo);
用户定义的变量保存在MySQL会话中,该会话绑定到数据库的单个连接。