日期:2014-05-16  浏览次数:20628 次

C#版SQL数据库操作类

废话说少吧,发代码才是硬道理。。。

?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace TestCSharpBasic
{
class SQLHelper
{
private string strError = null;
private int intCount = 0;
public SQLHelper()
{
}
/// <summary>
/// 记录sql日志,日志分等级,level=1是信息,等于0为异常
/// </summary>
/// <param name="str">日志信息</param>
/// <param name="level">日志等级</param>
public void Log(string str,int level)
{
string levelStr = "信息:";
if (level == 1)
{
levelStr = "信息:";
}
else
{
levelStr = "错误:";
}
Console.WriteLine(levelStr + str);
}
/// <summary>
/// 获取数据库连接
/// </summary>
/// <returns>数据库连接对象SqlConnection</returns>
public SqlConnection GetConn()
{// connstr = "Server=(local);DataBase=GlobalMeetings;Uid=sa;pwd=00"
string connStr = "Data Source=.\\SQLEXPRESS;Database=MyStockDB;Integrated Security=SSPI;";
SqlConnection conn = null;
try
{
conn = new SqlConnection(connStr);
}
catch (Exception ex)
{
Log(ex.Message,0);
// throw;
}
return conn;
}
/// <summary>
/// 公开属性ErrorMessage,反悔错误信息
/// </summary>
public string ErrorMessage
{
get
{
return strError;
}
}
/// <summary>
/// 查询数据库到dataset中
/// </summary>
/// <param name="SelectString">查询语句</param>
/// <param name="sqlConn">数据库连接</param>
/// <returns>数据结果集</returns>
public DataSet Select(string SelectString, SqlConnection sqlConn)
{
strError = "";
SqlConnection conn;
if (sqlConn == null)
{
conn = GetConn();
}
else
{
conn = sqlConn;
}
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand selectCmd = new SqlCommand(SelectString, conn);
selectCmd.CommandType = CommandType.Text;
adapter.SelectCommand = selectCmd;
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
catch (Exception e)
{
strError = "数据检索失败,错误信息:" + e.Message;
return null;
}
finally
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
}
// 更新 ,删除,插入
public bool Update(string UpdateString, SqlConnection SqlConn)
{
return udiDataBase(UpdateString,SqlConn);
}
public bool Delete(string DeleteString, SqlConnection SqlConn)
{
return udiDataBase(DeleteString, SqlConn);
}
public bool Insert(string InsertString, SqlConnection SqlConn)
{
return udiDataBase(InsertString, SqlCon