在windows窗体应用程序中有一个文本框和一个按钮。我想检查主键(persId)是否存在于我的sql数据库/数据集(Visual studio制作),当我在文本框中输入一个数字并按下按钮。我不知道如何将文本与数据库中的persId进行比较
如果persId存在,我想在一个新表单中填充两个文本框,并显示persId和persName。
我是c#编程新手,所以我可能错过了一些东西。我看了如何检查值是否存在于数据库从文本框c#,但无法找到答案。
提前感谢!
public void searchPersId(string persId)
{
SqlConnection conn = new SqlConnection();
SqlCommand myCommand = new SqlCommand("SELECT persId FROM Customers WHERE persId = @persId", conn);
myCommand.Parameters.AddWithValue("@persId", persId);
if (textBox1.Text = myCommand ) //I dont know how to compare the values of textbox with myCommand..
{
//Show values (persId and persName) in two textBoxes in a new form.
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
首先,对所有实现IDisposable
的东西(如连接)使用using
-语句来处置非托管资源并关闭连接,即使在出现错误的情况下。
然后您必须打开连接并使用ExecuteReader
获得数据读取器来检查是否至少有一个具有该ID的记录,您可以使用reader.HasRows
。如前所述,您还必须选择persName
。
using(var conn = new SqlConnection())
using(var myCommand = new SqlCommand("SELECT persId, persName FROM Customers WHERE persId = @persId", conn))
{
myCommand.Parameters.AddWithValue("@persId", persId);
conn.Open();
using(var rd = myCommand.ExecuteReader())
{
bool personExists = rd.HasRows;
if(personExists)
{
// advance the reader to the first record, presuming there is only one, otherwise use a loop while(rd.Read)
rd.Read();
string persName = rd.GetString(1); // second field
// ...
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
}
您也可以使用ExecuteScalar
public void searchPersId(string persId)
{
SqlConnection conn = new SqlConnection();
SqlCommand myCommand = new SqlCommand("SELECT persName FROM Customers WHERE persId = @persId", conn);
myCommand.Parameters.AddWithValue("@persId", persId);
object personName = myCommand.ExecuteScalar();
if(!string.IsNullOrEmpty(personName.ToString()))
//if (textBox1.Text = myCommand) //I dont know how to compare the values of textbox with myCommand..
{
//Show values (persId and persName) in two textBoxes in a new form.
textBox2.Text = personName.ToString();
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
首先必须执行命令。
SqlDataReader dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
// ... if it has rows then you know it match
}
else
{
// ... data doesn't exists
}
然后可以比较结果