using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
/// <summary>
/// 数据库数据存取操作类
/// 2009.3.19修改
/// 作者:小刚
/// </summary>
public class DataHelper
{
public DataHelper(string connString)
{
if (connString == null)
{
connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ToString();
}
else
connectionString = connString;
//初始化对象
sqlConnection = new SqlConnection(connectionString);
sqlCommand = new SqlCommand();
}
//初始化连接字符串(默认从web.config中"conn"节点读取)
private static string connectionString;
//数据库的连接对象
private SqlConnection sqlConnection;
//建立命令对象
private SqlCommand sqlCommand;
//获取DataReader对象
public SqlDataReader GetDataReader(string strCommand, params SqlParameter[] param)
{
PreCommand(sqlConnection, strCommand, param);
return sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
//获取DataSet对象
public DataSet GetDataSet(string strCommand, params SqlParameter[] param)
{
PreCommand(sqlConnection, strCommand, param);
SqlDataAdapter ad = new SqlDataAdapter(sqlCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
sqlConnection.Close();
return ds;
}
//返回第一行第一列那个对象
public object ExecuteScalar(string strCommand, params SqlParameter[] param)
{
PreCommand(sqlConnection, strCommand, param);
object temp = sqlCommand.ExecuteScalar();
sqlConnection.Close();
return temp;
}
//对数据库进行不返回对象的操作
public void ExecuteNon(string strCommand, params SqlParameter[] param)
{
PreCommand(sqlConnection, strCommand, param);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
//给SqlCommand添加参数
public void AddParms(SqlParameter[] param)
{
if (param != null)
{
foreach (SqlParameter p in param)
sqlCommand.Parameters.Add(p);
}
}
//执行前准备工作
public void PreCommand(SqlConnection sqlConnection, string strCommand, params SqlParameter[] param)
{
sqlCommand.CommandText = strCommand;
sqlCommand.Connection = sqlConnection;
AddParms(param);
if (sqlConnection.State == ConnectionState.Closed)
sqlConnection.Open();
}
}