上一节讲到了怎样使用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 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:[email protected]
新闻热点
疑难解答
图片精选