ITPub博客

首页 > Linux操作系统 > Linux操作系统 > C#:数据库SQL操作通用类

C#:数据库SQL操作通用类

原创 Linux操作系统 作者:iDotNetSpace 时间:2009-02-04 16:23:08 0 删除 编辑
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/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5347228