2017-07-08 98 views
4

我在名为'molasses_analysis'的表中有98列,我需要使用我的c#桌面应用程序插入记录。
我的代码示例如下。在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#代码多列?

+0

不是真的,不是。你可以通过列和列的值来使整个事情变得动态,但是你仍然需要执行最终的结果。 –

+0

不,没有AFAIK。您应该查看EntityFramework或类似的库。通过管理所有这些东西,为您节省大量时间。 – stybl

+0

你可以做的“最好的”是动态地建立你的SQL语句,有一个你需要添加值的字典或列表,以及你需要的值的类似列表(或相同的字典/列表)放置到这些列中,然后将所有这些使用循环组合在一起以连接正确的SQL并添加所有参数。 –

回答

4

简短的回答是否定的;不要用你使用局部变量填充每个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)); 
} 

:上面的代码是一个实施例使用字典和stringbuilders证明;应该研究,而不是复制粘贴。

1

如果您的财产名称和栏目名称相同,则此答案将对您有所帮助。 首先,让您的列与SQL代码如下

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'molasses_analysis'; 
//this returns column names and column types 

赐名然后分配表,列出其中包含列名

List<string> listColNames = new List<string>(); 

然后用循环创建你的SQLInsert串

foreach (string item in listColNames) { 
    params.Add(new SqlParameter("@" + item, item)); 
} 
相关问题