当前位置:网络资源中心文章中心网络编程ASP.NET教程 → 文章内容

使用函数传递参数来执行数据库操作 (1)

减小字体 增大字体 作者:Qesy  来源:0432web.com  发布时间:2008-5-16 9:47:06

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
比如
// 打开数据库

转自动态网制作指南 www.knowsky.com
public static SqlConnection OpenConnection()
{
SqlConnection mysqlConn = new SqlConnection(ConfigurationSettings.AppSettings["connstring"]);

try
{
mysqlConn.Open();
}
catch (Exception e)
{
//rethrow this exception
throw e;
}

return mysqlConn;
}

// 执行SQL返回DataSet
public static DataSet GetDataSet(string SQLQuery)
{
SqlConnection cn = DBObject.OpenConnection();
SqlDataAdapter da = new SqlDataAdapter(SQLQuery, cn);
DataSet ds = new DataSet();

da.Fill(ds);

//release resources
da.Dispose();
da = null;
cn.Close();
cn = null;

return ds;
}

// 执行SQL语句
public static void ExecuteUpdateQuery(string SQLQuery)
{
SqlConnection cn = DBObject.OpenConnection();
SqlCommand cmd = new SqlCommand();

cmd.CommandText = SQLQuery;
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
cmd.ExecuteNonQuery();

cn.Close();
cn = null;
}