2017-07-08 38 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)); 
} 
相關問題