using System; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Data.Common; using System.Collections.Generic; //引用后,直接修改与项目相同的命名空间就可直接使用:DXApplication5 namespace DXApplication5 { class DBHelper { //数据库链接字符串 public static string ConnString = "Data Source = 127.0.0.1;Initial Catalog = PulseSterilizer;User Id = sa;Password =sa;"; //建立数据库链接 public static SqlConnection conn = null; private static void InitConnection() { if (conn == null) conn = new SqlConnection(ConnString); if (conn.State == ConnectionState.Broken) { conn.Close(); conn.Open(); } if (conn.State == ConnectionState.Closed) { conn.Open(); } } //获取DataReader public static SqlDataReader GetDataReader(string str) { InitConnection(); SqlCommand cmd = new SqlCommand(str, conn); return cmd.ExecuteReader(CommandBehavior.CloseConnection); } //查询,获取DataSet public static DataSet GetDataSet(string sqlStr) { InitConnection(); DataSet ds = new DataSet(); SqlDataAdapter dap = new SqlDataAdapter(sqlStr, conn); dap.Fill(ds); conn.Close(); return ds; } //查询,获取DataTable public static DataTable GetDataTable(string sqlStr) { return GetDataSet(sqlStr).Tables[0]; } //增删改 public static int ExecuteNonQuery(string str) { InitConnection(); SqlCommand cmd = new SqlCommand(str, conn); int result = cmd.ExecuteNonQuery(); conn.Close(); return result; } //执行集合函数 public static object ExecuteScalar(string str) { InitConnection(); SqlCommand cmd = new SqlCommand(str, conn); object result = cmd.ExecuteScalar(); conn.Close(); return result; } } }