我在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.");
}
}
首先,using
对于所有实现方式(IDisposable
例如连接),都使用-statement来布置非托管资源并关闭连接,即使发生错误也是如此。
然后,您必须打开连接并用于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.");
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句