工作常用的操纵数据库的C#类

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
/// <summary>
/// db 的摘要说明
/// </summary>
public class db
{
 public db()
 {
  //
  // TODO: 在此处添加构造函数逻辑
  //
 }
    public static SqlConnection createConnection()
    {
        SqlConnection con = new SqlConnection("Data Source=IP地址;Initial Catalog=数据库名;Persist Security Info=True;User ID=用户;Password=密码");
        return con;
   
    }
    public int ExecSql(string Sql)
    {
        string constr = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
        SqlConnection myConnection = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand(Sql, myConnection);
        myConnection.Open();
        int ret = (int)cmd.ExecuteNonQuery();
        myConnection.Close();
        return ret;
    }
    public void Exec(string Sql)
    {//执行SQL语句
        string constr = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
        SqlConnection myConnection = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand(Sql, myConnection);
        myConnection.Open();
        cmd.ExecuteNonQuery();
        myConnection.Close();
    }

    //执行SqlDataReader
    public SqlDataReader GetReader(string Sql)
    {
        string constr = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
        SqlConnection conn = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand(Sql, conn);
        conn.Open();
        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return dr;
    }

    //执行DataSet加入到数据集
    public DataSet GetDatSet(string Sql)
    {
        string constr = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
        SqlConnection myConnection = new SqlConnection(constr);
        SqlDataAdapter da = new SqlDataAdapter(Sql, myConnection);
        DataSet ds = new DataSet();
        myConnection.Open();
        da.Fill(ds);
        myConnection.Close();
        return ds;
    }

================webConfig的配置文件=====================

<appSettings>
      <add key="ConnectionString" value="server=IP地址;database=库;uid=用户;Password=密码;"/>
  </appSettings>

你可能感兴趣的:(数据库)