如何检查数据库中是否存在记录 [英] How to check whether record exist in database or not
本文介绍了如何检查数据库中是否存在记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在检查
whether record exist in database or not
,但是收到错误
, but getting error as
Object reference not set to an instance of an object.
实际上如果记录存在于数据库中它会给出消息但是当它不存在时会发生错误
我尝试过:
Actually what happen if record exist in databse it give message but when not exist it give error
What I have tried:
string time = DateTime.Now.Day.ToString();
SqlConnection con5 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con5.Open();
SqlCommand check_User_Name = new SqlCommand("select * from attendance where date= convert(varchar(11), getdate(), 105) and name=@name", con5);
check_User_Name.Parameters.AddWithValue("@name", DropDownList1.Text);
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
ShowPopUpMsg("Already Saved Today!!");
DropDownList12.Enabled=false;
}
else
{
if (time == "12")
{
DropDownList12.Enabled = true;
}
}
con5.Close();
推荐答案
用替换
可以修复你的问题*
count(1)
replacing*
withcount(1)
would have fixed your issue
select count(1) from attendance where date= convert(varchar(11), getdate(), 105) and name=@name
试试这个:
Try This :
string query="select * from attendance where date= convert(varchar(11), getdate(), 105) and name=@name";
if(IsExist(query))
{
// Recored Exist
}
public bool IsExist(string Query)
{
bool check = false;
using (cmd = new SqlCommand(Query, con))
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows)
check = true;
}
sdr.Close();
con.Close();
return check;
}
这篇关于如何检查数据库中是否存在记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文