以前用command方法执行存储过程增加参数时,总是先用cmd.Parameters.Add方法来设置参数和参数类型,再用Parameters[0].Value来给参数赋值。以前的一个动作代码示例:

string strConn = "Data Source=.;Initial Catalog=HISDB;Integrated Security=True";

            using( SqlConnection conn = new SqlConnection(strConn))

            {

                conn.Open();

                SqlCommand cmd = new SqlCommand("AuditMessageInsert", conn);

                //设置命令类型为存储过程,没有设置的话会执行失败

                cmd.CommandType = CommandType.StoredProcedure;

                //设置参数名和类型

                cmd.Parameters.Add("@Target", SqlDbType.NChar);

                cmd.Parameters.Add("@Description", SqlDbType.NChar);

                cmd.Parameters.Add("@Actor", SqlDbType.NChar);

                cmd.Parameters.Add("@Time", SqlDbType.DateTime);

                cmd.Parameters.Add("@Computer", SqlDbType.NChar);

                //给参数赋值

                cmd.Parameters[0].Value = "ATarget";

                cmd.Parameters[1].Value = "Description";

                cmd.Parameters[2].Value = "Actor";

                cmd.Parameters[3].Value = DateTime.Now;

                cmd.Parameters[4].Value = "PC-Computer";

                cmd.ExecuteNonQuery();

            }

如果用Parameters.AddWithValue方法就不用这么麻烦了,可以直接加参数名和其值,不用再设置参数的类型,示例代码:

string strConn = "Data Source=.;Initial Catalog=HISDB;Integrated Security=True";

            using( SqlConnection conn = new SqlConnection(strConn))

            {

                conn.Open();

                SqlCommand cmd = new SqlCommand("AuditMessageInsert", conn);

               

                cmd.CommandType = CommandType.StoredProcedure;

               

             

                //增加参数:名称与类型 且与表中参数的顺序没关系

                cmd.Parameters.AddWithValue("@Actor", "Actor");

                cmd.Parameters.AddWithValue("@Target", "Target");

                cmd.Parameters.AddWithValue("@Description", "Description");

 

                cmd.Parameters.AddWithValue("@Computer", "Computer");

                cmd.Parameters.AddWithValue("@Time", DateTime.Now);

 

 

                cmd.ExecuteNonQuery();

            }

 

 

 

posted on 2018-03-09 11:20  whatgorun  阅读(1846)  评论(0编辑  收藏  举报