2

I am using MySQL with JDBC.

Is there a way I could use user-defined variables like "set @rank = 0;" in JDBC?

Specifically I want to implement ranking with 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);
4

2 回答 2

2

我是一名 MySQL DBA,但我对 JDBC 一无所知(除了“它与 Java 有关”,这足以让我觉得阅读它很痛苦)......但是,它看起来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() 调用应该可以完成您的意图。

或者,实际上,您只需要对数据库进行 2 次调用,因为前两个可以组合在一个查询中:

SET @rank = 0, @userCount = (select COUNT(*) from usertwo);

用户定义的变量保留在 MySQL 会话中,该会话绑定到与数据库的单个连接。

于 2013-10-30T03:28:57.073 回答
0

JDBC 是您的 java 代码与 MySQL DB 交互的方式,当您在 java 代码中创建查询/插入/更新时,您可以拥有任何您想要的 java 变量并将它们添加到查询字符串中。

当然,我可能误解了你的问题。你能详细说明一下吗?

于 2013-10-30T02:11:26.830 回答