Handling ExecuteScalar() when no results are returned

后端 未结 22 1082
猫巷女王i
猫巷女王i 2020-11-27 05:47

I am using the following SQL query and the ExecuteScalar() method to fetch data from an Oracle database:

sql = \"select username from usermst wh         


        
22条回答
  •  孤城傲影
    2020-11-27 06:09

    I'm using Oracle. If your sql returns numeric value, which is int, you need to use Convert.ToInt32(object). Here is the example below:

    public int GetUsersCount(int userId)
    {
        using (var conn = new OracleConnection(...)){
            conn.Open();
            using(var command = conn.CreateCommand()){
                command.CommandText = "select count(*) from users where userid = :userId";
                command.AddParameter(":userId", userId);            
                var rowCount = command.ExecuteScalar();
                return rowCount == null ? 0 : Convert.ToInt32(rowCount);
            }
        }
    }
    

提交回复
热议问题