c# - 在 C# 中使用主键向数据库插入行的最佳方法是什么

标签 c# mysql sql

抱歉我的标题含糊不清。基本上,我有一个调用记录应用程序,它使用带有 2 个表(客户和记录)的数据库来添加、删除和搜索记录。我在记录中有一个名为“CallID”的列,用于帮助保持调用的唯一性,因此我可以使用 CallID 来删除特定记录。然而问题出在我添加的通话功能上。我目前拥有它,因此 CallID 是列表中的项目数加 1:

private void addcall_btn_Click(object sender, EventArgs e)
    {
        try
        {

            //This is my addcall click event that inserts a row in 'Records' table using what the user has entered into the fields
            string sql = "INSERT Records (CustomerID, CallID, CustomerName, Telephone, DateAndTime, Status, Description) VALUES (@CustomerID, @CallID, @CustomerName, @Telephone, @DateAndTime, @Status, @Description)";
            SqlConnection conn = ConnectionString();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Connection = conn;
            cmd.Parameters.AddWithValue("CustomerID", customerID_cb.Text);
            cmd.Parameters.AddWithValue("CallID", (CallListBox.Items.Count + 1));
            cmd.Parameters.AddWithValue("DateAndTime", DateTime.Now);
            cmd.Parameters.AddWithValue("Status", status_cb.Text);
            cmd.Parameters.AddWithValue("Description", description_txt.Text);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

            MessageBox.Show("Record Created");
            this.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

您现在可能知道,简单地将列表中的项目数加一是一种笨拙的做法,并且在删除记录并且您想要添加更多记录后会导致问题。我想知道是否有一种方法可以做我正在尝试做的事情,但以更好的方式:)

谢谢!

最佳答案

CallID设置为自动递增

ALTER TABLE Records AUTO_INCREMENT=1

然后更改插入语句以排除该字段

INSERT Records (CustomerID, CustomerName, Telephone, DateAndTime, Status, Description) VALUES (@CustomerID, @CustomerName, @Telephone, @DateAndTime, @Status, @Description)

随后添加的任何行的数据库将处理 CallID 字段的值。

关于c# - 在 C# 中使用主键向数据库插入行的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23562517/

相关文章:

c# - 从一段曲面点中找到圆心

php - mysql对addslashes()的使用

sql - 删除SQL中的相似列

php - 从结果集中选择列到数组中

java - 将 MySQL 查询转换为 Java 中的实体管理器查询

c# - C# “var” 关键字在 VB.NET 中的等效项是什么?

c# - “返回”与“返回新”之间的区别

c# - Windows Phone - 裁剪位图图像

php - jquery - JSON 对象,格式为 <optgroup >,由 AJAX 从 PHP 和 MySQL 返回,在 Select2 中不起作用

PHP 脚本 + MySQL 只返回一行