查询永远不会为空
本文关键字:永远 查询 | 更新日期: 2023-09-27 18:35:40
我是编程和C#的新手,所以我正在尝试创建一个连接到sql Server的小应用程序,让我保存客户姓名,电话和地址。我面临一个问题是我的"检查数据是否已经存在"总是告诉它不为空并且无法保存。我将不胜感激。我知道这是非常菜鸟,很抱歉打扰了。
//Create and Open Connection
SqlConnection con = new SqlConnection("Data Source=KDC-LP''SQLEXPRESS;Initial Catalog=ClientsDB;Integrated Security=True");
SqlDataReader reader = null;
con.Open();
//Finding if data already exists
SqlCommand cmd = new SqlCommand("select name from clients where name = @name or phone1 in (@phone1, @phone2, @phone3) ", con);
cmd.Parameters.AddWithValue("@name", textbox1.Text);
cmd.Parameters.AddWithValue("@phone1", textbox2.Text);
cmd.Parameters.AddWithValue("@phone2", textbox3.Text);
cmd.Parameters.AddWithValue("@phone3", textbox4.Text);
reader = cmd.ExecuteReader();
//Saving or not ?
MessageBoxResult msg = MessageBox.Show("Are you sure you want to save the new data", " Save", MessageBoxButton.YesNo, MessageBoxImage.Question);
switch (msg)
{
case MessageBoxResult.Yes:
if (reader != null) //Name, Phones already exists
{
reader.Close();
MessageBoxResult notsaved = MessageBox.Show("Data already exists please check", "Save", MessageBoxButton.OK, MessageBoxImage.Warning);
}
else
{
//Saving
reader.Close();
SqlCommand cmdins = new SqlCommand("INSERT INTO Clients (name,phone1,phone2,phone3,address) Values ('" + textbox1.Text + "', '" + textbox2.Text + "', '" + textbox3.Text + "', '" + textbox4.Text + "', '" + textbox5.Text + "')", con);
cmdins.ExecuteNonQuery();
textbox1.Clear();
textbox2.Clear();
textbox3.Clear();
textbox4.Clear();
textbox5.Clear();
MessageBoxResult saved = MessageBox.Show("Data is Saved", "Save", MessageBoxButton.OK, MessageBoxImage.Information);
}
break;
//Not Saving
case MessageBoxResult.No:
{
MessageBoxResult msgno = MessageBox.Show("Data is not saved", "Save", MessageBoxButton.OK, MessageBoxImage.Warning);
}
break;
}
//Closing Connection
con.Close();
HasRows
属性告诉您查询是否返回行,您需要使用它:
if (reader.HasRows) //Name, Phones already exists
{
reader.Close();
MessageBoxResult notsaved = MessageBox.Show("Data already exists please check", "Save", MessageBoxButton.OK, MessageBoxImage.Warning);
}
ExecuteReader
总是返回一个读取器。如果查询未找到任何数据,仍会返回读取器。它只是不"包含"任何数据。所以这就是你需要检查的:
if (reader.HasRows) //Name, Phones already exists