using System;
using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; using System.Collections; using System.Windows.Forms; namespace WindowsFormsApplication1.ItemClass
{ public class SqlBaseClass { #region 代碼中用到的變量 SqlDataAdapter adp; DataSet ds; SqlCommand cmd; SqlDataReader dr; string connectionString = "server=.;database=db_GoodsManageData;User ID=sa;Pwd=aa"; SqlConnection conn; #endregion #region 鏈接數(shù)據(jù)庫(kù)
/// <summary> /// 鏈接數(shù)據(jù)庫(kù) /// </summary> /// <returns></returns> public SqlConnection GetCon() { conn = new SqlConnection(connectionString); conn.Open(); //打開(kāi)鏈接 return conn; //返回鏈接字符串 } #endregion #region 執(zhí)行SQL語(yǔ)句
/// <summary> /// 執(zhí)行SQL語(yǔ)句 /// </summary> /// <param name="cmdText">要執(zhí)行的SQL語(yǔ)句</param> /// <returns></returns> public bool GetExecute(string cmdText) { cmd = new SqlCommand(cmdText,GetCon()); try { cmd.ExecuteNonQuery(); return true; } catch (Exception ex) { MessageBox.Show("錯(cuò)誤:" + ex.Message, "錯(cuò)誤提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); return false; } finally { if (GetCon().State == ConnectionState.Open) { //如果數(shù)據(jù)庫(kù)鏈接處于打開(kāi)狀態(tài),,則關(guān)閉連接并釋放占用的資源 GetCon().Close(); GetCon().Dispose(); } } } #endregion #region 返回?cái)?shù)據(jù)集
/// <summary> /// 返回?cái)?shù)據(jù)集類型 /// </summary> /// <param name="cmdText">要執(zhí)行的SQL語(yǔ)句</param> /// <returns></returns> public DataSet GetDs(string cmdText) { try { adp = new SqlDataAdapter(cmdText,GetCon()); ds = new DataSet(); adp.Fill(ds); return ds; } catch (Exception ex) { MessageBox.Show("錯(cuò)誤:" + ex.Message, "錯(cuò)誤提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); return null; } finally { if (GetCon().State == ConnectionState.Open) { //如果數(shù)據(jù)庫(kù)鏈接處于打開(kāi)狀態(tài),,則關(guān)閉連接并釋放占用的資源 GetCon().Close(); GetCon().Dispose(); } } } #endregion #region 返回SqlDataReader類型數(shù)據(jù)
/// <summary> /// 返回SqlDataReader類型數(shù)據(jù) /// </summary> /// <param name="cmdText">要執(zhí)行的SQL語(yǔ)句</param> /// <returns></returns> public SqlDataReader GetReader(string cmdText) { cmd = new SqlCommand(cmdText ,GetCon()); try { dr = cmd.ExecuteReader(); return dr; } catch (Exception ex) { MessageBox.Show("錯(cuò)誤:" + ex.Message, "錯(cuò)誤提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); return null ; } finally { if (GetCon().State == ConnectionState.Open) { //如果數(shù)據(jù)庫(kù)鏈接處于打開(kāi)狀態(tài),,則關(guān)閉連接并釋放占用的資源 GetCon().Close(); GetCon().Dispose(); } } } #endregion } } |
|
來(lái)自: shymi > 《SQL數(shù)據(jù)庫(kù)》