数据库操作类DBHelper(C#版)

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

namespace Db
{
    public class DBHelper
    {
		//数据库连接字符串
        public static string connString = "server=.;database=SuperKTV;uid=sa;pwd=123456;";

		//数据库连接对象
        private static SqlConnection conn = null;

		//初始化数据库连接
        private static void InitConnection() {
			//如果连接对象不存在,则创建对象
            if (conn == null)
                conn = new SqlConnection(connString);
			//如果连接对象关闭,则打开连接
            if (conn.State == ConnectionState.Closed)
                conn.Open();
			//如果连接对象中断,则重启连接
            if (conn.State == ConnectionState.Broken)
            {
                conn.Close();
                conn.Open();
            }
        }
		
		//查询,获取DataReader
        public static SqlDataReader GetDataReader(string sql) {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql, conn);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
		
		//查询,获取DataTable
        public static DataTable GetDataTable(string sql) {
            InitConnection();
            DataTable table = new DataTable();
            SqlDataAdapter dap = new SqlDataAdapter(sql, conn);
            dap.Fill(table);
            conn.Close();
            return table;
        }
		
		//增删改
        public static bool ExecuteNonQuery(string sql) {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql, conn);
            int result = cmd.ExecuteNonQuery();
            conn.Close();
            return result > 0;
        }
		
		//执行聚合函数
        public static Object ExecuteScalar(string sql) {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql, conn);
            object result = cmd.ExecuteScalar();
            conn.Close();
            return result;
        }
    }
}
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页