日期:2012-06-08 浏览次数:20473 次
上一节讲到了怎样使用ADO.NET来查询数据,这节讲怎么样运行SQL的SELECT、INSERT和UPDATE命令及存储过程
1、存储过程
C#的代码如下:
/// <summary>
/// 存储过程参数结构
/// </summary>
public struct ProcParam
{
public string ParamName;
public string ParamValue;
public System.Data.SqlDbType ParamType ;
}
/// <summary>
/// 执行一个返回数据集的存储过程
/// </summary>
/// <param name="strProcName">存储过程名称</param>
/// <param name="alParamName" >参数名称</param>
/// <param name="alParamValue" >参数值</param>
/// <param name="constring">数据连接串</param>
/// <returns></returns>
public static System.Data.SqlClient.SqlDataReader ExecProcedure(string strProcName,System.Collections.ArrayList alParamName,System.Collections.ArrayList alParamValue,string constring)
{
System.Data.SqlClient.SqlConnection cn=new System.Data.SqlClient.SqlConnection (constring);
cn.Open ();
System.Data.SqlClient.SqlCommand cmd=new System.Data.SqlClient. SqlCommand ();
cmd.Connection =cn;
cmd.CommandType =System.Data.CommandType.StoredProcedure ;
cmd.CommandText =strProcName;
for(int i=0;i<alParamName.Count ;i++)
{
System.Data.SqlClient.SqlParameter param=new System.Data.SqlClient.SqlParameter (alParamName[i].ToString (),alParamValue[i].ToString ());
cmd.Parameters.Add (param);
}
System.Data.SqlClient.SqlDataReader dr;
dr=cmd.ExecuteReader ();
return dr;
}
上述代码可以执行任意参数的存储过程(返回一个数据集)
2、直接SQL命令
/// <summary>
/// 执行一个返回字符串的SQL SCRIPT
/// </summary>
/// <param name="constring" >连接串</param>
/// <param name="SQL_COMMAND" >SQL命令</param>
/// <returns>返回数据集</returns>
public static string GetDataString(string SQL_COMMAND,string constring)
{
System.Data.SqlClient.SqlConnection cn=new System.Data.SqlClient.SqlConnection (constring);
cn.Open ();
System.Data.SqlClient.SqlCommand cmd=new System.Data.SqlClient. SqlCommand ();
cmd.Connection =cn;
cmd.CommandType =System.Data.CommandType.Text ;
cmd.CommandText =SQL_COMMAND;
string str="";
try
{
str=cmd.ExecuteScalar().ToString ();
}
catch(System.Data.SqlClient.SqlException e)
{
System.Diagnostics.Debug.WriteLine (e.Message );
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine (ex.Message );
}
return str;
}
/// <summary>
/// 执行一个无返回的SQL
/// </summary>
/// <param name="SQL_COMMAND"></param>
/// <param name="constring"></param>
/// <returns></returns>
public static void Executesql(string SQL_COMMAND,string constring)
{
System.Data.SqlClient.SqlConnection cn=new Syste