〖上一节讲到了怎样使用ADO.NET来查询...... 上一节讲到了怎样使用ADO.NET来查询数据,这节讲怎么样运行SQL的SELECT、INSERT和UPDATE命令及存储过程 1、存储过程 C#的代码如下: /// /// 存储过程参数结构 /// public struct ProcParam { public string ParamName; public string ParamValue; public System.Data.SqlDbType ParamType ; } /// /// 执行一个返回数据集的存储过程 /// /// 存储过程名称 /// 参数名称 /// 参数值 /// 数据连接串 /// 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 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命令 /// /// 执行一个返回字符串的SQL SCRIPT /// /// 连接串 /// SQL命令 /// 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; } /// /// 执行一个无返回的SQL /// /// /// /// public static void Executesql(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; try { cmd.ExecuteNonQuery (); } catch(System.Data.SqlClient.SqlException e) { System.Diagnostics.Debug.WriteLine (e.Message ); } catch(Exception ex) { System.Diagnostics.Debug.WriteLine (ex.Message ); } } 以上代码建议放在一个类中,如果有问题请与我联系msn:ilxc8292@hotmail.com |
|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )
GMT+8, 2024-9-30 23:25 , Processed in 0.270985 second(s), 12 queries , Gzip On, MemCache On.
Powered by Discuz! X3.5
© 2001-2023 Discuz! Team.