gpt4 book ai didi

c# - SqlCommand.ExecuteScalar 避免空值

转载 作者:行者123 更新时间:2023-11-29 04:46:49 24 4
gpt4 key购买 nike

关键是我有这段代码

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?

最佳答案

只需在调用 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();
}

关于c# - SqlCommand.ExecuteScalar 避免空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17843748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com