C#的自動拼接Sql語句Insert方法及思路


思路:

  1、想想插入語句,大概是這樣的一個框架:INSERT INTO 表名 (數據庫列名) values (值)

  2、這里要3個變量是不固定的,分別是:表名、數據庫列名、值;

    a.表名我們這里很容易可以獲取到

    b.數據庫列名,我們可以遍歷容器獲取控件的Name屬性

    c.值,我們可以遍歷容器獲取控件的Text屬性

 1 private static Dictionary<string, string> GetDicKeyValue(Control controlBox)
 2         {
 3             //遍歷容器獲取控件的Name屬性和Text屬性,存放到鍵值中,用於以下的拼接sql
 4             Dictionary<string, string> dic = new Dictionary<string, string>();
 5             foreach (Control item in controlBox.Controls)
 6             {
 7                 if (item is Label || item is PictureBox)
 8                 {
 9                     continue;
10                 }
11                 if (item is TextBox)
12                 {
13                     dic.Add(item.Name.Substring(3, item.Name.Length - 3), item.Text.Trim());
14                     continue;
15                 }
16                 if (item is ComboBox)
17                 {
18                     dic.Add(item.Name.Substring(3, item.Name.Length - 3), item.Text);
19                     continue;
20                 }
21                 if (item is DateTimePicker)
22                 {
23                     dic.Add(item.Name.Substring(3, item.Name.Length - 3), item.Text);
24                     continue;
25                 }
26                 if (item is CheckBox)
27                 {
28                     string result = ((CheckBox)item).Checked ? "1" : "0";
29                     dic.Add(item.Name.Substring(3, item.Name.Length - 3), result);
30                     continue;
31                 }
32             }
33             return dic;
34         }
View Code

好了,我們通過上面一個函數已經獲取到控件的Name屬性(即數據庫列名)和Text屬性(即值),下面開始組裝Sql語句

 1 private void button1_Click(object sender, EventArgs e)
 2         {
 3             Dictionary<string, string> dic = GetDicKeyValue(panel1);
 4             string autoMatchSql = string.Empty;
 5             StringBuilder Sb1 = new StringBuilder();
 6             StringBuilder Sb2 = new StringBuilder();
 7             foreach (KeyValuePair<string, string> item in dic)
 8             {
 9                 Sb1.Append(item.Key.Trim()).Append(",");
10                 Sb2.Append("'").Append(item.Value.Trim()).Append("'").Append(",");
11             }
12             autoMatchSql += "INSERT INTO 表名 ";
13             autoMatchSql += " (" + Sb1.ToString().Substring(0, Sb1.Length - 1) + ") VALUES ";
14             autoMatchSql += " (" + Sb2.ToString().Substring(0, Sb2.Length - 1) + ")";
15         }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM