自用SqlHelper

using System.Data;
using System.Data.SqlClient;
using System.Configuration;


class SqlHelper
{

private SqlConnection Connection;

private SqlCommand Command;

/// <summary>
/// 创建一个数据库连接并打开该连接
/// </summary>
/// <param name="connStr">连接字符串</param>
public SqlHelper( string connStr)
{
Connection
= new SqlConnection(connStr);
Open();
}


/// <summary>
/// 打开数据库连接
/// </summary>
public void Open()
{
if (Connection.State != ConnectionState.Open)
Connection.Open();
}

/// <summary>
/// 关闭数据库连接
/// </summary>
public void Close()
{
if (Connection.State != ConnectionState.Closed)
Connection.Close();
}

/// <summary>
/// 执行带参数的sql语句(插入、删除、修改),返回执行T-SQL后受影响行数
/// </summary>
/// <param name="para">SQL参数,如没有则填null</param>
/// <param name="cmdText">SQL语句</param>
/// <returns>返回受影响的行数</returns>
public int UpData(string cmdText, params SqlParameter[] para)
{

Command
= new SqlCommand(cmdText, Connection);
if (para != null)
{
foreach (SqlParameter p in para)
{
Command.Parameters.Add(p);
}
}
return Command.ExecuteNonQuery();
}

/// <summary>
/// 执行带参数的sql语句(select语句),返回SqlDataReader数据流
/// </summary>
/// <param name="cmdText">SQL语句</param>
/// <param name="para">SqlParameter,如没有则填null</param>
public SqlDataReader GetDataReader(string cmdText, params SqlParameter[] para)
{
Command
= new SqlCommand(cmdText, Connection);
if (para != null)
{
foreach (SqlParameter p in para)
{
Command.Parameters.Add(p);
}
}
return Command.ExecuteReader(CommandBehavior.CloseConnection);
}

/// <summary>
/// 执行带参数的sql语句(select语句),返回DataSet
/// </summary>
/// <param name="cmdText">SQL语句</param>
/// <param name="para">参数列表,如果没有填null</param>
public DataSet GetDataSet(string cmdText,params SqlParameter[] para)
{
Command
= new SqlCommand(cmdText, Connection);
if (para != null)
{
foreach (SqlParameter p in para)
{
Command.Parameters.Add(p);
}

}

SqlDataAdapter da
= new SqlDataAdapter();
DataSet ds
= new DataSet();
da.SelectCommand
= Command;
da.Fill(ds);
return ds;
}
}
其实这个SqlHelper在现在看来用处已经不算太大了,因为最近换了工作,公司主要使用oracle.下次再更新个通用版的吧,最近也学到不少新知识,包括架构方面的学习.
posted on 2011-07-05 23:59  江小花儿  阅读(425)  评论(0编辑  收藏  举报