/*************最近写了一个类,专门和数据库打交道的,请各位评价评价,好的与不好的一律照单全收*****************/
using System;
using System.Data;
using System.Data.SqlClient;
namespace WebRoot
{
class Sql
{
SqlConnection conn;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
/// <summary>
/// 连接数据库
/// </summary>
/// <param name="server">服务器名称</param>
/// <param name="database">数据库名称</param>
/// <param name="uid">登录帐号</param>
/// <param name="pwd">登录密码</param>
public Sql(string server,string database,string uid,string pwd)
{
conn = new SqlConnection("server=" + server + "; database=" + database + "; uid=" + uid + "; pwd=" + pwd);
}
/// <summary>
/// 查询数据库
/// </summary>
/// <param name="sql">T-select语句</param>
/// <param name="tableName">表的别名</param>
/// <returns>数据集</returns>
public DataSet runSelect(string sql,string tableName)
{
try
{
da = new SqlDataAdapter(sql,conn);
ds = new DataSet();
da.Fill(ds,tableName);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if(conn.State == ConnectionState.Open)
conn.Close();
}
return ds;
}
/// <summary>
/// 查询数据库
/// </summary>
/// <param name="sql">T-select语句</param>
/// <returns>数据集</returns>
public DataSet runSelect(string sql)
{
try
{
da = new SqlDataAdapter(sql,conn);
ds = new DataSet();
da.Fill(ds);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if(conn.State == ConnectionState.Open)
conn.Close();
}
return ds;
}
/// <summary>
/// 对数据的增、删、改
/// </summary>
/// <param name="sql">增、删、改的T-SQL语句</param>
public void runUpdate(string sql)
{
try
{
cmd = new SqlCommand(sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if(conn.State == ConnectionState.Open)
conn.Close();
}
}
/// <summary>
/// 获取表的字段名称
/// </summary>
/// <param name="tableName">表名</param>
/// <returns>数据集</returns>
public DataSet getHeader(string tableName)
{
try
{
string sql = "select * from " + tableName + " where 1 = 0";
da = new SqlDataAdapter(sql,conn);
ds = new DataSet();
da.Fill(ds);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if(conn.State == ConnectionState.Open)
conn.Close();
}
return ds;
}
}
}