连接数据库与执行SQL语句
public void Test1() { 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(); } }
public void Test2() { 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(); } }