C#:資料庫SQL操作通用類

iDotNetSpace發表於2009-02-04
1: using System;
   2: using System.Data;
   3: using System.Data.SqlClient;
   4:  
   5:  
   6: namespace QxtIntface
   7: {
   8:     class DBCom
   9:     {
  10:         // 獲取與資料庫的連線
  11:         public static SqlConnection GetSqlConnection()
  12:         {
  13:             try
  14:             {
  15:                 SqlConnection scon = new SqlConnection(Global.sConStr);
  16:                 return scon;
  17:             }
  18:             catch(Exception ex)
  19:             { 
  20:                 System.Windows.Forms.MessageBox.Show("資料庫連線錯誤!"+ex.Message);
  21:                 return null;
  22:             }
  23:         }
  24:         public static SqlConnection GetSqlConnection(string sConStr)
  25:         {
  26:             try
  27:             {
  28:                 SqlConnection scon = new SqlConnection(sConStr);
  29:                 return scon;
  30:             }
  31:             catch (Exception ex)
  32:             {
  33:                 System.Windows.Forms.MessageBox.Show("資料庫連線錯誤!" + ex.Message);
  34:                 return null;
  35:             }
  36:         }
  37:         
  38:         // 返回指定資料庫的資料集
  39:         public static DataSet GetExeQuery(string selectCmd)
  40:         {
  41:             SqlConnection con = GetSqlConnection();
  42:             con.Open();
  43:             DataSet ds = new DataSet();
  44:             SqlDataAdapter da = new SqlDataAdapter(selectCmd, con);
  45:             da.Fill(ds);
  46:             con.Close();
  47:             return ds;
  48:         }
  49:  
  50:         // 執行非查詢命令
  51:         public static int ExeNoneQuery(string sCmd)
  52:         {
  53:             int nResult;
  54:             SqlConnection con = GetSqlConnection();
  55:             con.Open();
  56:             SqlCommand cmd = new SqlCommand(sCmd, con);
  57:             nResult = cmd.ExecuteNonQuery();
  58:             return nResult;
  59:         }
  60:  
  61:         //返回資料查詢的第一個欄位值(查詢指定表的資料行數)
  62:         public static int ExeScalar(string selectTableName)
  63:         {
  64:             string selectCmd = "select count * from " + selectTableName;
  65:             SqlConnection con = GetSqlConnection();
  66:             con.Open();
  67:             SqlCommand cmd = new SqlCommand(selectCmd, con);
  68:             return Convert.ToInt32(cmd.ExecuteScalar());
  69:         }
  70:     }
  71: }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-545255/,如需轉載,請註明出處,否則將追究法律責任。

相關文章