您的位置:首页 > 数据库

C# 一个SqlHelper例子

2013-06-17 14:12 316 查看
using System;
using System.Collections.Generic;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

/// <summary>
/// Summary description for SqlHelper
/// </summary>
public class SqlHelper : IDisposable
{
#region 基本属性
private string _lastError;

public string LastError
{
get
{
return _lastError;
}
set
{
_lastError = value;
}
}

public static string ConnectionString = ConfigurationSettings.AppSettings["DBConnectionString"];

protected SqlConnection cnn;

#endregion

public SqlHelper()
{
this._lastError = string.Empty;
try
{
cnn = new SqlConnection(ConnectionString);
cnn.Open();
}
catch (Exception ex)
{
this._lastError = ex.Message;
throw ex;
}
}

///执行sql
public bool Execute(string sql)
{
try
{
this._lastError = string.Empty;
using (SqlCommand cmd = new SqlCommand(sql.Trim(), cnn))
{
cmd.ExecuteNonQuery();
return true;
}
}
catch (Exception ex)
{
this._lastError = ex.Message;
return false;
}
}

///执行,返回DataReader
public SqlDataReader Reader(string sql)
{
try
{
this._lastError = string.Empty;
using (SqlCommand cmd = new SqlCommand(sql.Trim(), cnn))
{
SqlDataReader dr = cmd.ExecuteReader();
return dr;
}
}
catch (Exception ex)
{
this._lastError = ex.Message;
return null;
}

}

///执行sql,返回DataTable
public DataTable Query(string sql)
{
this._lastError = string.Empty;

DataTable dt = new DataTable();

try
{
using (SqlDataAdapter da = new SqlDataAdapter(sql.Trim(), cnn))
{
da.Fill(dt);
return dt;
}
}
catch (Exception ex)
{
this._lastError = ex.Message;
return null;
}

}

///执行sql,返回DataSet
public DataSet Query(string sql, object inputNull)
{
this._lastError = string.Empty;

DataSet ds = new DataSet();

try
{
using (SqlDataAdapter da = new SqlDataAdapter(sql.Trim(), cnn))
{
da.Fill(ds);
return ds;
}
}
catch (Exception ex)
{
this._lastError = ex.Message;
return null;
}

}

///执行sql,返回一串字符
public string GetValue(string sql, int ColumnIndex)
{
try
{
this._lastError = string.Empty;

using (SqlDataReader dr = this.Reader(sql))
{
if (dr.Read())
{
return dr[ColumnIndex].ToString().Trim();
}
return string.Empty;
}
}
catch (Exception ex)
{
this._lastError = ex.Message;
return string.Empty;
}
}

public string GetValue(string sql, string ColumnName)
{
try
{
this._lastError = string.Empty;

using (SqlDataReader dr = this.Reader(sql))
{
if (dr.Read())
{
return dr[ColumnName].ToString().Trim();
}
return string.Empty;
}
}
catch (Exception ex)
{
this._lastError = ex.Message;
return string.Empty;
}
}

~SqlHelper()
{
this.Dispose(false);
}

private bool disposed = false;

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if (!this.disposed && disposing)
{
try
{
cnn.Close();
cnn.Dispose();
}
catch
{
}
}
disposed = true;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: