c# - 在 C# 中的表中插入多个值

标签 c#

我在名为“molasses_analysis”的表中有 98 列,我需要使用我的 C# 桌面应用程序插入记录。
示例 我的代码如下。

    string insert_sql = @"insert into molasses_analysis(mo_entry_date, mo_entry_time, mo_code, mo_brix, mo_pol, mo_purity, mo_crtd_by) " +
    " values(@entry_date, @entry_time, @mol_code, @brix, @pol, @purity, @crtd_by)";
    try
        {
         List<SqlParameter> param = new List<SqlParameter>();
         param.Add(new SqlParameter("@entry_date", entry_date));
         param.Add(new SqlParameter("@entry_time", entry_time));
         param.Add(new SqlParameter("@mol_code", mol_code));
         param.Add(new SqlParameter("@brix", brix));
         param.Add(new SqlParameter("@pol", pol));
         param.Add(new SqlParameter("@purity", purity));
         param.Add(new SqlParameter("@crtd_by", crtd_by));
        int inserted_rows = SqlHelper.ExecuteNonQuery(dbConn.sqlConn(),CommandType.Text, insert_sql, param.ToArray());
        }
catch (Exception ex)
      {
        MessageBox.Show("Data not saved!\nError message - "+ex.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }

这里我只使用了七个字段/列,但是为 98 列编写这样的代码并为每一列分配 Sql 参数 将是非常忙碌和痛苦的。 我的问题是,是否有任何更清晰、更好的代码来使用 c# 代码插入多列?

最佳答案

简短的回答是否定的;与您使用局部变量填充每个 SqlParameter 的方式不同。

一个解决方案是,如果每个局部变量都存储在 Dictionary 中(键/值对)你可以使用 StringBuilder并迭代您的字典键以构建 SQL 查询字符串。在同一个循环中,您可以添加每个 SqlParameter

using System.Collections.Generic; // for dictionary
using System.Text; // for stringbuilder

// ...

// create a dictionary then use a literal to make it easier to populate
Dictionary<string, string> data = new Dictionary<string, string>
{
    { "entry_date", "SOMEVALUE1" }, 
    { "entry_time", "SOMEVALUE2" }
    // add more params and values here...
};

// start our query and params list
StringBuilder query = new StringBuilder("YOUR QUERY STARTS HERE");
List<SqlParameter> params = new List<SqlParameter>();

// iterate over each key/value pair, appending to the query and params list
foreach (KeyValuePair<string, string> pair in data) {
    query.Append("@" + pair.Key);
    params.Add(new SqlParameter(pair.Key, pair.Value));
}

注意:以上代码是一个示例,用于演示如何使用字典和字符串生成器;应该研究它,而不是复制粘贴。

关于c# - 在 C# 中的表中插入多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44990272/

相关文章:

c# - 有方法的属性?

c# - 使用 C# 在 XML 中用日期替换字符串

c# - 参数验证失败。不可能为所有参数提供有效值。 (rsParameterError) sql 报告 2008

c# - 有没有更好的方法来设置 linq 中项目列表的公共(public)属性

c# - 使用线程时是否需要锁定 "read only"服务?

c# - 允许 Form1 关闭而不关闭 C# 中的应用程序?

c# - 从应用程序创建 Sqlite 嵌入式数据库

c# - 进程可执行文件启动的 .NET 事件

c# - 点网核心 3.1 : How to use AddJsonFile with absolute path to file?

c# - Web Socket Server v13 RFC 6455 客户端不接收消息