SqlCommand.ExecuteScalar避免null

时间:2013-07-24 20:00:01

标签: c# mysql scalar

问题是我有这个代码

var ojv = xmd.ExecuteScalar().ToString();
        if (ojv != null)
        {
            Console.WriteLine(ojv);
            var up = CreateQuery();
            up.CommandText = "UPDATE characters SET items=@items WHERE accId=@accId AND charId=@charId;";
            up.Parameters.AddWithValue("@items", ojv);
            up.Parameters.AddWithValue("@accId", acc.AccountId);
            up.Parameters.AddWithValue("@charId", charId);
            up.ExecuteNonQuery();
            var del = CreateQuery();
            del.CommandText = "DELETE FROM shop WHERE accId=@accId AND chrId=@chrId;";
            del.Parameters.AddWithValue("@accId", acc.AccountId);
            del.Parameters.AddWithValue("@chrId", charId);
            del.ExecuteNonQuery();
        }

但是如果没有ovj它返回null,我需要避免这种情况,有没有办法让ExecuteScalar在没有找到值的情况下不会返回null?

2 个答案:

答案 0 :(得分:2)

ExecuteScalar返回一个数字,如果没有结果集,则返回null,因此首先需要检查null(在应用ToString()之前),然后解析为整数(或大整数,或小数,无论你需要什么)并检查大于零。

答案 1 :(得分:2)

在调用ToString()之前检查null。

    var result = xmd.ExecuteScalar();
        if (result != null)
        {
            var ojv = result.ToString();
            Console.WriteLine(ojv);
            var up = CreateQuery();
            up.CommandText = "UPDATE characters SET items=@items WHERE accId=@accId AND charId=@charId;";
            up.Parameters.AddWithValue("@items", ojv);
            up.Parameters.AddWithValue("@accId", acc.AccountId);
            up.Parameters.AddWithValue("@charId", charId);
            up.ExecuteNonQuery();
            var del = CreateQuery();
            del.CommandText = "DELETE FROM shop WHERE accId=@accId AND chrId=@chrId;";
            del.Parameters.AddWithValue("@accId", acc.AccountId);
            del.Parameters.AddWithValue("@chrId", charId);
            del.ExecuteNonQuery();
        }