如何使用 c# 从 sql 中的"整数类型"列中获取 Null 值


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{

static void Main(string[] args)
{
int? a = null;
String connectionString = @"server=LT-1113SQL2016;database=Employee;user=sa;password=envision1!";
Dictionary<int,String> d = new Dictionary<int,string>();
List<KeyValuePair<int?, String>> l = new List<KeyValuePair<int?, String>>();
using(SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("select id,Name from details", con);
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// Employee e = new Employee();
Console.WriteLine(reader.GetValue(0));
int id =(int)reader.GetInt32(0);//getting exception in this line
// if(reader.IsDBNull(id))
String  Name = reader.GetValue(1).ToString();
l.Add(new KeyValuePair<int?,string>(id,Name) );
}
Console.WriteLine("Enter the Key");
bool b = false;
int mykey = Convert.ToInt32(Console.ReadLine());
String Value="";
foreach (KeyValuePair<int?, String> i in l)
{
if(i.Key == mykey)
{
Value=i.Value;
b = true;
}

// Console.WriteLine(i.Value);
}
if(b==true)
{
Console.WriteLine(Value);
}
else
{
Console.WriteLine("SORRY DATA NOT PRESENT");
}
//Console.ReadLine();
}
}
}
}

我的表有列 id 并将一行命名为 varchar(20( name="ABC" 和 int id="NULL">

请提前帮助我谢谢

尝试通过指定columnnameIsDBNull

int id = reader.IsDBNull("id") ? 0 : reader.GetInt32(reader.GetOrdinal("id"))

相关内容

  • 没有找到相关文章

最新更新