使用SqlCommand的,如何通过的winform在SQL表的多个参数添加到它的对象,插入它的、多个、对象、参数

由网友(收起你的虚伪、给老子滚)分享简介:我在我的winform 10文本框,我需要保存输入这些文本框到SQL数据库表中的10列文本。因此,对于这个将我写的:I have ten textboxes in my winform, and i need to save the text typed in these textboxes into 10 colu...

我在我的winform 10文本框,我需要保存输入这些文本框到SQL数据库表中的10列文本。因此,对于这个将我写的:

I have ten textboxes in my winform, and i need to save the text typed in these textboxes into 10 columns of a sql database table. so, for this shall i write :

INSERT INTO item (c1,c2,c3...,c10) values (@a,@b....@j) 

cmd.Parameters.Add("@a",SqlDbType.Varchar)
cmd.Parameteres["@a"].Value=textbox1.Text;

cmd.Parameters.Add("@b",SqlDbType.Varchar)
cmd.Parameteres["@b"].Value=textbox2.Text;.
.
.
.
.
cmd.Parameters.Add("@j",SqlDbType.Varchar)
cmd.Parameteres["@j"].Value=textbox10.Text;

或每个文本框十个单独的查询:

OR ten separate queries for each textbox:

INSERT INTO item (c1) values (@a)
cmd.Parameters.Add("@a",SqlDbType.Varchar)
cmd.Parameteres["@a"].Value=textbox1.Text;

INSERT INTO item (c2) values (@b) 
cmd.Parameters.Add("@b",SqlDbType.Varchar)
cmd.Parameteres["@b"].Value=textbox2.Text;.
.
.
INSERT INTO item (c10) values (@j)
cmd.Parameters.Add("@j",SqlDbType.Varchar)
cmd.Parameteres["@j"].Value=textbox10.Text;

或者,请提出一个有效的code。

or, please suggest an efficient code.

如何添加多个参数在单个语句到CMD?这可能吗?

How to add multiple parameters to cmd in a single statement? is it possible?

推荐答案

您可以使用扩展方法,像这样的:

You can use an extension method, like this:

public static class DbCommandExtensions
{
    public static void AddInputParameters<T>(this IDbCommand cmd,
        T parameters) where T : class
    {
        foreach (var prop in parameters.GetType().GetProperties())
        {
            object val = prop.GetValue(parameters, null);
            var p = cmd.CreateParameter();
            p.ParameterName = prop.Name;
            p.Value = val ?? DBNull.Value;
            cmd.Parameters.Add(p);
        }
    }
}

然后调用它是这样的:

Then call it like this:

cmd.AddInputParameters(new { a = textBox1.Text, b = TextBox2.Text, /* etc */ });

我用在几个项目,没有任何问题。

I've used that in a few projects with no problems.

阅读全文

相关推荐

最新文章