我是编程和 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();