方法完成但数据未插入SQL数据库

时间:2015-04-21 08:36:07

标签: c# sql winforms localdb

我有一个方法应该将用户详细信息保存到Visual Studio上的本地数据库,下面的方法有问题

   private void btnSaveDetails_Click(object sender, EventArgs e)
    {
        //var IssueDate = this.dtpIssueDate.Value.ToString("yyyy-MM-dd HH:mm:ss") + "')";
        //var ExipryDate =this.dtpExpiryDate.Value.ToString("yyyy-MM-dd HH:mm:ss") + "')";
        var mainMenu = new frmMainMenu();
        SqlConnection sc = new SqlConnection();
        SqlCommand com = new SqlCommand();
        sc.ConnectionString = (Properties.Settings.Default.BioEngineering);
        sc.Open();
        com.Connection = sc;


        com.Parameters.AddWithValue("@Forename", this.txtFirstName.Text);
        com.Parameters.AddWithValue("@Surname", this.txtLastName.Text);
        com.Parameters.AddWithValue("@Company", this.txtCompany.Text);
        com.Parameters.AddWithValue("@SecurityLevel", this.cboSecurityLevel.Text);
        com.Parameters.AddWithValue("@IssueDate", this.dtpIssueDate.Value);
        com.Parameters.AddWithValue("@ExpiryDate", this.dtpExpiryDate.Value);
        com.Parameters.AddWithValue("@CardID", this.cboCardID.Text);

        com.CommandText = "INSERT INTO Users (Forename, Surname, Company, SecurityLevel, IssueDate, ExpiryDate, CardID) VALUES (@Forename,@Surname,@Company,@SecurityLevel,@IssueDate,@ExpiryDate,@CardID)";
        com.ExecuteNonQuery();
        sc.Close();
        this.Hide();
        mainMenu.Show();
    }

我没有错误,当我在com.ExecuteNonQuery添加断点时,它似乎有正确的数据....任何想法?我首先认为它是连接字符串,但看到其他类似格式的网站,所以不要认为它

1 个答案:

答案 0 :(得分:0)

在向命令添加任何参数之前,请尝试设置CommandText属性。简单地说,把这个:

com.CommandText = "INSERT INTO Users (Forename, Surname, Company, SecurityLevel, IssueDate, ExpiryDate, CardID) VALUES (@Forename,@Surname,@Company,@SecurityLevel,@IssueDate,@ExpiryDate,@CardID)";

之前:

com.Parameters.AddWithValue("@Forename", this.txtFirstName.Text);
com.Parameters.AddWithValue("@Surname", this.txtLastName.Text);
com.Parameters.AddWithValue("@Company", this.txtCompany.Text);
com.Parameters.AddWithValue("@SecurityLevel", this.cboSecurityLevel.Text);
com.Parameters.AddWithValue("@IssueDate", this.dtpIssueDate.Value);
com.Parameters.AddWithValue("@ExpiryDate", this.dtpExpiryDate.Value);
com.Parameters.AddWithValue("@CardID", this.cboCardID.Text);

希望这有帮助。

相关问题