c#连接sqlserver

时间:2022-02-04 02:20:27

using System;
using System.Collections.Generic;
using System.Web;
using System.Data.OleDb;
using System.Data;
using System.Data.SqlClient;
namespace httpClient.script
{
   public class SqlConnDB
    {
        SqlConnection conn = null; //连接数据库的对象
                                   /// <summary>
                                   /// 构造函数,连接数据库,数据库连接字符在web.Config文件的AppSettings下的conStr
                                   /// </summary>
        public SqlConnDB()
        {
            if (conn == null)
            {
                //判断连接是否为空
                string conString = "server=(local);database=demo;Trusted_Connection=SSPI";//连接数据库的字符串
                //string conString = System.Configuration.ConfigurationManager.AppSettings["conStr"];//连接数据库的字符串
                conn = new SqlConnection(conString);
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();//打开数据库连接
                }
            }
        }
        /// <summary>
        /// 从数据库中查询数据的,返回为DataSet
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataSet query(string sql)
        {
            DataSet ds = new DataSet();//DataSet是表的集合
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);//从数据库中查询
            da.Fill(ds);//将数据填充到DataSet
            connClose();//关闭连接
            return ds;//返回结果
        }
        /// <summary>
        /// 更新数据库
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int update(string sql)
        {
            if (conn == null) { return -1; }
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();//打开数据库连接
            }
            SqlCommand oc = new SqlCommand();//表示要对数据源执行的SQL语句或存储过程
            oc.CommandText = sql;//设置命令的文本
            oc.CommandType = CommandType.Text;//设置命令的类型
            oc.Connection = conn;//设置命令的连接
            int x = oc.ExecuteNonQuery();//执行SQL语句
            connClose();//关闭连接
            return x;  //返回一个影响行数
        }
        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        public void connClose()
        {
            if (conn.State == ConnectionState.Open)
            {
                //判断数据库的连接状态,如果状态是打开的话就将它关闭
                conn.Close();
            }
        }
    }
}