C# 执行存储过程
SqlParameter[] paras = BuildParas(id, time, name);
bool bRet = ExcuteProcedure(“数据库连接字符串”, "存储过程名", paras, "表名");
public static SqlParameter[] BuildParas(string Id, DateTime Time, string Name)
{
SqlParameter[] paras = new SqlParameter[3];
SqlParameter para1 = new SqlParameter();
para1.Direction = ParameterDirection.Input;
para1.ParameterName = "@pid";
para1.SqlDbType = SqlDbType.VarChar;
para1.Size = 32;
para1.Value = Id;
paras[0] = para1;
SqlParameter para2 = new SqlParameter();
para2.Direction = ParameterDirection.Input;
para2.ParameterName = "@ptime";
para2.SqlDbType = SqlDbType.DateTime;
para2.Value = DateTime.Parse(Time);
paras[1] = para2;
SqlParameter para3 = new SqlParameter();
para3.Direction = ParameterDirection.Input;
para3.ParameterName = "@pname";
para3.SqlDbType = SqlDbType.VarChar;
para3.Size = 20;
para3.Value = Name;
paras[2] = para3;
return paras;
}
public static bool ExcuteProcedure(string strDataBaseInfo, string procedureName, SqlParameter[] paras, string strTableName)
{
bool bRet = false;
SqlCommand cmd = null;
SqlConnection con = new SqlConnection(strDataBaseInfo);
try
{
con.Open();
cmd = new SqlCommand("select count(*) from " + strTableName + " where id='" + paras[0].Value.ToString() + "'", con);//目的是保证id唯一
int nExistCount = int.Parse(cmd.ExecuteScalar().ToString());//查询结果的第一行的第一列
if (nExistCount > 0)
{
return true;
}
cmd = null;
cmd = new SqlCommand(procedureName, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
if (paras != null && paras.Length > 0)
{
for (int i = 0; i < paras.Length; i++)
{
cmd.Parameters.Add(paras[i]);
}
}
int nCount = cmd.ExecuteNonQuery();
if (nCount != -1)
{
bRet = true;
}
}
catch (Exception ex)
{
}
finally
{
if (cmd != null)
cmd.Parameters.Clear();
if (con.State == ConnectionState.Open)
con.Close();
}
return bRet;
}