整理数据库操作类以便取用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration; namespace Eshop
{
public class DbManage
{
#region 类中的全局变量-数据连接字符串
public static string strcon = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString.ToString();//连接字符串,使用Windows登录方式
#endregion #region 构造函数
/// <summary>
/// 构造函数,初始化时连接数据库
/// </summary>
public DbManage()
{
strcon = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString.ToString();
}
#endregion #region 返回SqlDataReader-ExceRead类型的数据
/// <summary>
/// 此方法返回SqlDataReader-ExceRead类型的参数
/// </summary>
/// <param name="Sqlcom"></param>
/// <returns></returns>
public static SqlDataReader ExceRead(string Sqlcom)
{
SqlConnection con = new SqlConnection(strcon);
try
{
con.Open();
SqlCommand com = new SqlCommand(Sqlcom,con);
SqlDataReader read = com.ExecuteReader(); return read;
}
catch (SqlException E)
{ throw new Exception(E.Message);
}
}
#endregion #region 返回SqlDataReader-ExceScalar类型的数据
/// <summary>
/// 此方法返回SqlDataReader-ExceScalar类型的参数
/// </summary>
/// <param name="Sqlcom"></param>
/// <returns></returns>
public static object ExceScalar(string Sqlcom)
{
SqlConnection con = new SqlConnection(strcon);
try
{
con.Open();
SqlCommand com = new SqlCommand(Sqlcom, con);
object strdata = com.ExecuteScalar();
return strdata; }
catch (SqlException E)
{ throw new Exception(E.Message);
}
}
#endregion #region 返回DataSet类型的数据并获得tableName参数
/// <summary>
/// 此方法返回一个DataSet类型
/// </summary>
/// <param name="strsql">要执行的SQL语句</param>
/// <param name="tablename"></param>
/// <returns></returns>
public static DataSet GetDataSet(string strsql,string tablename)
{
//定义一个数据集,用来赋值给应用程序的一个数据集
SqlConnection con = new SqlConnection(strcon);
DataSet ds = new DataSet();
try
{
SqlDataAdapter DA = new SqlDataAdapter(strsql,con);
DA.Fill(ds,tablename);
}
catch (SqlException E)
{ throw new Exception(E.Message);
} return ds;
}
#endregion #region 执行SQL语句,包括增删改
/// <summary>
/// 此方法用来执行SQL语句
/// </summary>
/// <param name="strSqlCom">要执行的SQL语句</param>
/// <returns></returns>
public static bool ExceSQL(string strSqlCom)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand com = new SqlCommand(strSqlCom,con); try
{
//判断数据库是否为连接状态
if (con.State == ConnectionState.Closed)
{
con.Open();
}
//执行SQL语句
com.ExecuteNonQuery();
//SQL语句执行成功,返回true值
return true;
}
catch
{
//SQL语句执行失败,返回false值
return false;
}
finally
{
//关闭数据库连接
con.Close();
}
}
#endregion
}
}
05-11 11:19