Using SqlCommand , how to add multiple parameters to its object , insertion via winform in sql table

大憨熊 提交于 2019-11-30 05:32:57

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.

I think you can use Parameters.AddWithValue() method.

cmd.Parameters.AddWithValue("@j",textbox10.Text);
cmd.Parameters.AddWithValue("@k",textbox11.Text);
cmd.Parameters.AddWithValue("@l",textbox12.Text);

The 2 'solutions' that you suggest in your question, are semantically different. Which one you should use, depends on your table-layout.

The first solution inserts one record in the table, the second insert statement inserts one record (row) for every value (textbox).

Difficult to give a good answer here, since we do not know what you're going to save in that table, and thus , we cannot say how you should save it (how you save it, is inherintly dependent on the way you should call the SQL insert statement).

You could use a function like this:

void AddParams(DBCommand cmd,params object[] parameters)
{
    if (parameters != null)
    {
        int index = 0;
        while (index < parameters.Length)
        {
            cmd.Parameters.AddWithValue("@"+(string)parameters[index], parameters[index + 1]);
            index += 2;
        }
    }
}

Not the best one probably, but functional. Call link this:

AddParams(a,"test1",b,3,c,DateTime.Now);

Or you can use an extension like suggested from @Matt Hamilton to add this function in DBCommand class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!