不能用这两种方法检查空值c#数据读取器空值错误
本文关键字:空值 数据 错误 读取 检查 两种 方法 不能 | 更新日期: 2023-09-27 17:50:59
问题是;我在class内部使用此代码,并从主窗体调用class。我得到了错误关于我的数据阅读器不能得到空值。如何检查来自sp的数据是否为空?作为内部代码,如果我看到null,我改变它并返回为outval (0000)
public string opt()
{
string strng= "";
string outval= "";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["nmrbg"].ConnectionString;
conn.Open();
SqlCommand cmd = new SqlCommand("nmp_sp_sy", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
// if (rdr.HasRows)
// {
// while (rdr.Read())
// {
// int nm= rdr.GetInt32(0);
// strng= Convert.ToString(nm);
// outval= strng;
// }
// }
while (rdr.Read())
{
int nm= rdr.GetInt32(0);
strng= Convert.ToString(nm);
outval= strng;
}
if (!rdr.HasRows)
{
outval= "0000";
}
rdr.Close();
rdr.Dispose();
conn.Close();
conn.Dispose();
return outval;
}
Begin
Begin Transaction
DECLARE @minSira int
select @minSira=Min(siraNo)
from nmr_tbl_srbklynlr
where turId=2 and aktifPasif=1
UPDATE top (1) nmr_tbl_srbklynlr
SET aktifPasif = 0
Where siraNo=@minSira
select @minSira
Commit Transaction
End
试试这个代码
public string opt()
{
string strng= "";
string outval= "";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["nmrbg"].ConnectionString;
conn.Open();
SqlCommand cmd = new SqlCommand("nmp_sp_sy", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
// if (rdr.HasRows)
// {
// while (rdr.Read())
// {
// int nm= rdr.GetInt32(0);
// strng= Convert.ToString(nm);
// outval= strng;
// }
// }
while (rdr.Read())
{
if(rdr["ColumnName"] != DBNull.Value)
{
int nm= rdr.GetInt32(0);
strng= Convert.ToString(nm);
outval= strng;
}
else
{
outval= "0000";
}
}
if (!rdr.HasRows)
{
outval= "0000";
}
rdr.Close();
rdr.Dispose();
conn.Close();
conn.Dispose();
return outval;
}
测试在null上返回值:数据库可以很好地在int上返回null。使用:将IDisposable
封装到中,以防止资源在正常流和异常流上泄漏。
public string opt() {
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["nmrbg"].ConnectionString)) {
conn.Open();
using (SqlCommand cmd = new SqlCommand("nmp_sp_sy", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataReader rdr = cmd.ExecuteReader()) {
// If there's no records to read (rdr is empty) return default
if (!rdr.Read())
return "0000";
Object rawData = rdr.GetValue(0);
if (Object.RefrenceEquals(null, rawData))
return "0000"; // <- Or whatever on null value
else
return rawData.ToString();
}
}
}
}