如何使用键值对构建插入查询

时间:2017-09-22 19:28:47

标签: c#

我正在尝试构建一个使用所有文本框名称的插入查询(可以在KeyValuePair<>中说出这些键),所以我不必输入所有命名参数(即文本框名称)但是而只是使用列表中的所有文本框名称。

我的代码如下:

private void buttonInsert_Click(object sender, EventArgs e)
{
    using (members.DBConnection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\qbc.mdb"))
    {
        members.DBConnection.Open();

        // find out which textboxes were filled out
        foreach (Control ctrl in Controls)
        {
            if (ctrl is TextBox)
            {
                members.textBoxes.Add(new System.Collections.Generic.KeyValuePair<string, string>(((TextBox)ctrl).Name, ((TextBox)ctrl).Text));
            }
        }

        for (int i = 0; i < members.textBoxes.Count; i++)
        {
                members.DBCommand.Parameters.AddWithValue(String.Format("@{0}", members.textBoxes[i].Key),
                       !string.IsNullOrEmpty(members.textBoxes[i].Value) ? members.textBoxes[i].Value : "");
        }

        using (members.DBCommand = new System.Data.OleDb.OleDbCommand("INSERT INTO members (fullName, birthday, phoneNumber, address, email, status, anniversary)" +
                    "VALUES(@" + members.textBoxes + ")", members.DBConnection))
        {
            try
            {
                members.DBCommand.ExecuteNonQuery();
            }
            catch (System.Data.OleDb.OleDbException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
         }
    }
 }

但是当我尝试使用members.textBoxes.Key时(在使用members.DBCommand行上,它会给我一个错误:

 List<KeyValuePair<string, string>> does not contain a definition for 'Key' and no extension method named 'Key' accepting a first argument of 'List<KeyValuePair<string,string>>' could be found (are you missing a using directive or assembly reference?)

如果有办法,我真的不想在查询的VALUES部分输入所有文本框的名称。

任何帮助将不胜感激

谢谢!

更新 -

我已经更改了我的代码,因此它遵循了一些答案

 private void buttonInsert_Click(object sender, EventArgs e)
    {
        // associate the textboxes with the column fields in the database
        // long but meh
        // household head textboxes
        textBox_hh.Tag        = "fullName";
        textBoxHHBirthday.Tag = "birthday";
        textBoxPhone.Tag      = "phoneNumber";
        textBoxAddress.Tag    = "address";
        textBoxEmail.Tag      = "email";
        textBoxStatus.Tag     = "status";



        using (members.DBConnection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\qbc.mdb"))
        {
            members.DBConnection.Open();

            // find out which textboxes were filled out
            foreach (var textbox in Controls.Cast<Control>().OfType<TextBox>())
            {
                 var pair = new KeyValuePair<string, string>(textbox.Tag.ToString(), textbox.Text);

                 members.textBoxes.Add(pair);
            }

            var columnNames = string.Join(", ", members.textBoxes.Select(m => m.Key));

            var parameterNames = string.Join(", ", members.textBoxes.Select(m => $"@{m.Key}"));

            var query = $"INSERT INTO members ({columnNames}) VALUES ({parameterNames})";



            using (members.DBCommand = new System.Data.OleDb.OleDbCommand(query, members.DBConnection))
            {
                try
                {
                    foreach (var member in members.textBoxes)
                    {
                        members.DBCommand.Parameters.AddWithValue($"@{member.Key}", member.Value);
                    }

                    members.DBCommand.ExecuteNonQuery();
                }
                catch (System.Data.OleDb.OleDbException ex)
                {
                   MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   return;
                }
            }
        }
    }

但很遗憾,现在查询只是INSERT INTO members () VALUES ()

2 个答案:

答案 0 :(得分:0)

如果你的表格栏目是&#39;名称与文本框名称相同:

     using (members.DBCommand = new System.Data.OleDb.OleDbCommand("INSERT INTO members (" + String.Join(", ", members.textBoxes.Select(tb => tb.Key).ToArray()) + ")" +
              " VALUES(" +  String.Join(", ", members.textBoxes.Select(tb => "'" + tb.Value+ "'").ToArray()) +   ")", members.DBConnection))

否则,如果列表textboxes的项目按列的顺序添加,请尝试以下操作:

using (members.DBCommand = new System.Data.OleDb.OleDbCommand("INSERT INTO members (fullName, birthday, phoneNumber, address, email, status, anniversary)" +
                  " VALUES(" +  String.Join(", ", members.textBoxes.Select(tb => "@" + tb.Value).ToArray()) +   ")", members.DBConnection))

答案 1 :(得分:0)

我认为您现在花费更多时间自动生成插入查询,然后手动输入。

为了生成正确的插入查询,您需要循环列名称和列值(读取参数名称) 你绝对应该使用SqlParameters作为值

var columnNames = string.Join(", ", members.textBoxes.Select(m => m.Key));
var parameterNames = string.Join(", ", members.textBoxes.Select(m => $"@{m.Key}"));
var query = $"INSERT INTO members ({columnNames}) VALUES ({parameterNames})";

using (var command = new OleDbCommand(query, members.DBConnection))
{
    foreach (var member in members.textBoxes)
    {
        command.Parameters.AddWithValue($"@{member.Key}", member.Value)
    }

    command.ExecuteNonQuery();
}

您可以使用.Tag属性

将列名与文本框关联
textboxFullName.Tag = "fullName";

然后创建以列名作为键的键值对

foreach (var textbox in Controls.Cast<Control>().OfType<TextBox>())
{
    var pair = new KeyValuePair<string, string>(textbox.Tag.ToString(), textbox.Text);
    members.textBoxes.Add(pair);
}