【问题标题】:C# edit button to Access databaseC#编辑按钮到Access数据库
【发布时间】:2016-10-06 17:45:56
【问题描述】:

我有一个库存界面的特定部分,它要求员工从组合框中选择他或她的姓名,然后将产品扫描到分配给该员工姓名的表中。

我的好奇心是:当点击 EDITADDDELETE 按钮时,它会从 Switch - Case 语句中知道要在哪个表中执行此功能,上面有该员工姓名.问题是,对于每个员工来说,这段代码都很长,特别是对于 9 名员工,每个员工都有一个 Switch - Case 语句。

关于如何简化或缩短代码的任何建议?我事先了解我未能使用的 参数化 SQL。只是想先完成这个。

private void btnAdd_Click(object sender, EventArgs e)
    {
        ActiveControl = txtSerialN;
        if (!string.IsNullOrEmpty(txtSerialN.Text) && !string.IsNullOrEmpty(cboEmpName.Text))

            switch (cboEmpName.SelectedItem.ToString().Trim())
            {
                case "John Doe":
                    try
                    {
                        connection.Open();
                        OleDbCommand command = new OleDbCommand();
                        command.Connection = connection;

                        command.CommandText = "INSERT INTO JohnDoe(SerialNumber,PartNumber,DateEntered,Customer) values ('" + txtSerialN.Text + "','" + txtPart.Text + "','" + txtDate.Text + "','" + txtCustomer.Text + "')";
                        command.ExecuteNonQuery();
                        MessageBox.Show("Inventory Added".PadLeft(23));

                        connection.Close();
                        txtSerialN.Clear();
                        txtPart.Clear();
                        txtDate.Clear();
                        txtCustomer.Clear();

                        command.CommandText = "SELECT * FROM JohnDoe ORDER BY PartNumber";
                        OleDbDataAdapter db = new OleDbDataAdapter(command);
                        DataTable dt = new DataTable();
                        db.Fill(dt);
                        dataGridEmpParts.DataSource = dt;
                    }

                    catch (OleDbException)
                    {
                        string strmsg = "THIS SERIAL NUMBER ALREADY EXISTS ! , Please try again";
                        MessageBox.Show(strmsg, "YOU CAN'T ENTER THE SAME ONE AGAIN", MessageBoxButtons.OK,
                        MessageBoxIcon.Exclamation,
                        MessageBoxDefaultButton.Button1);
                        connection.Close();
                    }
                    break;
            }
    }

【问题讨论】:

  • 警告您的代码极易受到 sql 注入攻击
  • 是的.....我知道。这是 9 个人使用的本地接口,他们对尝试破解接口没有兴趣。
  • 请确认您的实际问题是什么? “问题是,对于每个员工来说,这段代码都很长,尤其是对于 9 名员工,每个员工都有一个 Switch - Case 语句。”
  • 你的意思是员工人数越多,switch语句就越多

标签: c# sql sql-parametrized-query


【解决方案1】:

我怀疑通过更改数据库可以更有效地解决此问题。甚至可能就像为员工姓名添加一个字段一样简单。

【讨论】:

    【解决方案2】:

    我宁愿建立一个查找表,其中包含 EmployeeName、AssignedTable 等列,并根据参数值动态构造命令文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多