【问题标题】:How to create Java method to count rows in Oracle table如何创建 Java 方法来计算 Oracle 表中的行数
【发布时间】:2012-07-23 13:51:31
【问题描述】:

我想创建可以计算 Oracle 表中行数的 Java 方法。到目前为止,我做了这个:

public int CheckDataDB(String DBtablename, String DBArgument) throws SQLException {
    System.out.println("SessionHandle CheckUserDB:"+DBArgument);
    int count;
    String SQLStatement = null;

    if (ds == null) {
        throw new SQLException();
    }

    Connection conn = ds.getConnection();
    if (conn == null) {
        throw new SQLException();
    }

    PreparedStatement ps = null;

    try {
        conn.setAutoCommit(false);
        boolean committed = false;
        try {
            SQLStatement = "SELECT count(*) FROM ? WHERE USERSTATUS = ?";

            ps = conn.prepareStatement(SQLStatement);
            ps.setString(1, DBtablename);
            ps.setString(2, DBArgument);

            ResultSet result = ps.executeQuery();

            if (result.next()) {
                count = result.getString("Passwd");
            }

            conn.commit();
            committed = true;
        } finally {
            if (!committed) {
                conn.rollback();
            }
        }
    } finally {
        /* Release the resources */
        ps.close();
        conn.close();
    }

    return count;
}

我想用于不同的表。这是我无法解决的问题:

count = result.getString("row"); 

你能帮我解决这个问题吗?

【问题讨论】:

  • 如果不知道列名,可以使用java.sql.ResultSetMetaData#getColumnName

标签: java sql oracle11g


【解决方案1】:
count = result.getInt(1);

这是必需的,因为 count 是 int。并且可以指定查询返回的行的索引,不需要通过名称来访问。

但你也可以这样做:

count = result.getInt("count(*)");

【讨论】:

    【解决方案2】:

    应该这样做:

    count = result.getInt("count(*)");  
    

    您需要使用与查询中指定的名称相同的名称来获取值。你也可以让你的

    count = result.getString("row"); 
    

    将查询更改为

    SQLStatement = "SELECT count(*) as row FROM ? WHERE USERSTATUS = ?";
    

    【讨论】:

    • 查看link 了解更多信息。
    【解决方案3】:

    您不能在 SQL 查询中使用绑定变量代替数据库对象,可以吗?它只能用于参数绑定。 试试这个,

    "SELECT count(*) as row_count FROM " + DBtablename + " WHERE USERSTATUS = ?";
    

    这可能容易受到 SQL 注入的攻击,因此您可能需要检查 DBtablename 参数是否为有效的数据库对象名称(即最多 30 个字节长,不包含空格,并且仅包含数据库对象标识符的有效字符)。

    count = result.getInt("row_count");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多