如何使用 C# 将 SQL 数据库服务器连接到 WindowsForm 中的用户控件



我尝试将数据库连接到桌面应用程序中的用户控件。 捕获块正在运行。 任何人都可以在这里看到任何错误吗?有人可以帮助找到正确的代码来连接SQL Server管理工作室2014到Windows表单应用程序?

我已经尝试了我们用于 Windows 表单的代码。 但它不起作用。是否有任何不同的代码用于用户控制数据库连接?

SqlCommand cmd;
SqlConnection con;
private void btnsave_Click(object sender, EventArgs e) {
    try {
      con = new SqlConnection(@ "Data Source=LAPTOP-EN6B5ABV;Initial Catalog=nature;Integrated Security=True");
      con.Open();
      cmd = new SqlCommand("INSERT INTO crop" + " (cropid, cropname, scnname, noofplant, culdate, ferttimeperiod, harvetimeperiod, addeddate,lifetime,lifetimeperiod) VALUES (@cropid, @cropname, @scnname, @noofplant, @culdate, @ferttimeperiod, @harvetimeperiod, @addeddate,@lifetime,@lifetimeperiod)", con);
      cmd.Parameters.AddWithValue("@cropid", txtcropid.Text);
      cmd.Parameters.AddWithValue("@cropname", txtcropname.Text);
      cmd.Parameters.AddWithValue("@scnname", txtscnname.Text);
      cmd.Parameters.AddWithValue("@noofplant", textBox1.Text);
      cmd.Parameters.AddWithValue("@culdate", dateTimePicker1.Text);
      cmd.Parameters.AddWithValue("@ferttimeperiod", comfert.SelectedItem);
      cmd.Parameters.AddWithValue("@harvetimeperiod", comboBox1.SelectedItem);
      cmd.Parameters.AddWithValue("@lifetime", textBox2.Text);
      cmd.Parameters.AddWithValue("@lifetimeperiod", combolifetime.SelectedItem);
      cmd.Parameters.AddWithValue("@addeddate", addeddate.Text);
      cmd.ExecuteNonQuery();
      con.Close();
    } catch (Exception) {
      MessageBox.Show("something went wrong in database server");
    }

我希望插入数据。

这是我

的代码,我得到了正确的输出。存在与日期时间选取器值相关的错误。当获取日期时间选择器的选定值时,它被赋予了一个错误。

我使用此语句将日期插入数据库。

cmd.Parameters.AddWithValue("@culdate", Convert.ToDateTime(dateTimePicker1.Value));
string date =DateTime.Now.ToShortDateString();
cmd.Parameters.AddWithValue("@cropid", txtcropid.Text);
cmd.Parameters.AddWithValue("@cropname", txtcropname.Text);
cmd.Parameters.AddWithValue("@scnname", txtscnname.Text);
cmd.Parameters.AddWithValue("@noofplant", txtnoofplant.Text);
cmd.Parameters.AddWithValue("@culdate", Convert.ToDateTime(dateTimePicker1.Value));
cmd.Parameters.AddWithValue("@ferttimeperiod", txtharvtime.Text);
cmd.Parameters.AddWithValue("@fert", comfert.SelectedItem.ToString());
cmd.Parameters.AddWithValue("@harvtimeperiod", txtharvtime.Text);
cmd.Parameters.AddWithValue("@harv", comboBox1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("@addeddate", date);
cmd.Parameters.AddWithValue("@lifetimeperiod", txtlifetime.Text);
cmd.Parameters.AddWithValue("@life", combolifetime.SelectedItem.ToString());
cmd.ExecuteNonQuery();
con.Close();
string msg = "Crop Details are successfully saved...";
string title = "Saved";
System.Media.SystemSounds.Asterisk.Play();
MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.None);

最新更新