插入命令的ASP.NET类代码 [英] ASP.NET class code for insert command

查看:83
本文介绍了插入命令的ASP.NET类代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要用于为插入命令创建类文件的代码.
我只想在类文件中一次创建插入命令,然后下一次我只在每个页面中调用该函数.但是我该如何为插入命令创建类,因为每次我都有不同的列数来插入值时.
我认为它创建使用数组.但是我做不到.

请帮助我.....提前感谢

I want the code for create a class file for insert command.
I want to create insert command at only one times in class file then next time i just call the function in every page. But how can i create class for insert command because every time i have different number of columns to insert value.
I think it creates using array. But i can''t do it.

Please help me.....Thanks in advance

推荐答案

看看params关键字:它使您可以使用零个或多个参数列表:
Look at the params keyword: it lets you have a zero or more list of parameters:
public void Insert(string table, params string data)
   {
   ...
   }
...
Insert("myTable", "hello", "there");
Insert("myTable", "A", "B", "C", "D");

然后,您要做的就是确定要传递的参数类型-您可能需要查看KeyValuePair,因为您将需要一个列名和一个值.

All you have to do then is work out what kind of parameters you want to pass - you might want to look at KeyValuePair since you will need a Column name and a value.


public class DAL
{





public void InsertWithParam(string statement, SqlParameter[] param)
    {
        using (SqlConnection con = new SqlConnection(constr.Connect()))
            try
            {
                SqlCommand cmd = new SqlCommand(statement, con);
                cmd.CommandType = CommandType.Text;
                for (int i = 0; i < param.Length; i++)
                {
                    cmd.Parameters.Add(param[i]);
                }
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            catch(SqlException ex)
            {
                string message = "Insertion Error In Query";
                message += ex.Message;
                throw new Exception(message);
            }
            finally
            {
                con.Close();
            }
    }


}
将其作为函数,在其他页面中将该函数称为


}
make this as a function and in other page call this function as

public void InsertHoliday(string Holiday, DateTime HolyDate)
   {
       sql = string.Empty;
       sql = "insert into Holiday_Mstr (Holiday,HolidayDate)values(@Holiday,@HolidayDate)";
       SqlParameter[] param = new SqlParameter[2];
       param[0] = new SqlParameter("@Holiday", Holiday);
       param[1] = new SqlParameter("@HolidayDate", HolyDate);
       dal.InsertWithParam(sql, param);
   }


这篇关于插入命令的ASP.NET类代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆