单例模式
class DBHelper { private static readonly string strConn = "Data Source=.;Integrated Security=true;Initial Catalog=myDB"; private static SqlConnection sqlConn = null; private static DBHelper dbHelper = null; /// <summary> /// 数据库连接对象实例 /// </summary> private DBHelper() { if (sqlConn == null) { sqlConn = new SqlConnection(strConn); } } /// <summary> /// 取得/创建对象实例 /// </summary> /// <returns></returns> internal static DBHelper GetIntance() { if (dbHelper == null) { dbHelper = new DBHelper(); } return dbHelper; } /// <summary> /// 打开数据库连接 /// </summary> private void Open() { if (sqlConn.State == ConnectionState.Closed) { sqlConn.Open(); } } /// <summary> /// 关闭数据库连接 /// </summary> private void Close() { if (sqlConn.State == ConnectionState.Open) { sqlConn.Close(); } } public int ExecuteSql(string strSql, SqlParameter[] para) { SqlCommand sqlCmd = new SqlCommand(strSql, sqlConn); if (para != null) { sqlCmd.Parameters.AddRange(para); } Open(); int objResult = sqlCmd.ExecuteNonQuery(); Close(); return objResult; } public DataSet GetSqlDataSet(string strSql, SqlParameter[] para) { SqlCommand sqlCmd = new SqlCommand(strSql, sqlConn); if (para != null) { sqlCmd.Parameters.AddRange(para); } SqlDataAdapter sqlAdp = new SqlDataAdapter(sqlCmd); DataSet ds = new DataSet(); sqlAdp.Fill(ds); return ds; } }
//调用实例 private static void GetDBList() { DBHelper dbHelper = DBHelper.GetIntance(); DataSet ds = dbHelper.GetSqlDataSet("SELECT TOP 20 [StuId],[StuName] FROM [Student]", null); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { Console.WriteLine(ds.Tables[0].Rows[i][0].ToString() + ds.Tables[0].Rows[i][1].ToString()); } }