【问题标题】:method completes but data is not inserted into SQL database方法完成但数据未插入 SQL 数据库
【发布时间】:2015-04-21 08:36:06
【问题描述】:

我有一个方法可以将用户详细信息保存到 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 添加断点时,它似乎有正确的数据......有什么想法吗?我一开始以为是连接字符串,但看到其他格式相似的网站,所以不要认为是它

【问题讨论】:

  • 这个插入查询在您的数据库管理器中有效吗?
  • 您是否尝试过运行 SQL Server Profiler 来确定查询是否实际针对您的数据库运行?
  • 确保将BioEngineering 设置配置为连接字符串。然后,您可以使用内置对话框来配置连接字符串。这是为了确保您始终拥有正确的连接字符串。
  • @YannickMeeus 查询不运行
  • 将你的方法包裹在try-catch 中并检查ExecuteNonQuery() 是否抛出异常。我猜parametersconnection string 有问题

标签: c# sql winforms localdb


【解决方案1】:

在将任何参数添加到命令之前,请尝试设置您的 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);

希望这会有所帮助。

【讨论】:

  • 不幸的是仍然没有成功:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 2013-04-24
  • 1970-01-01
相关资源
最近更新 更多