我是Programming and 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();
答案 0 :(得分:2)
HasRows
属性告诉您查询是否返回了行,您需要使用:
if (reader.HasRows) //Name, Phones already exists
{
reader.Close();
MessageBoxResult notsaved = MessageBox.Show("Data already exists please check", "Save", MessageBoxButton.OK, MessageBoxImage.Warning);
}
答案 1 :(得分:1)
ExecuteReader
总是会让读者回复。如果查询未找到任何数据,则仍会返回读者。它只是不“包含”任何数据。这就是您需要检查的内容:
if (reader.HasRows) //Name, Phones already exists