简体   繁体   中英

SqlCommand.ExecuteScalar avoid null

The thing is I have this code

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();
        }

But if theres no ovj it return null, I need to avoid that, is there any way so the ExecuteScalar wont return null if no value is found?

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

Just check for null before you call ToString().

    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();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM