生如夏花

这是一个多美丽又遗憾的世界,我们就这样抱着笑着还流着泪 我从远方赶来赴你一面之约,痴迷流连人间我为她而狂野
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

数据库操作类精简版

Posted on 2006-12-27 08:57  陈欠扁  阅读(238)  评论(0)    收藏  举报

using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Collections;
using System.Configuration;

/// <summary>
/// Summary description for SqlHelper
/// </summary>
public class SqlHelper
{
    //public static string CONN_STR = @"Server=HUDENGWEN\SQLEXPRESS;Database=MQSDB;Trusted_Connection=True";
    public static string CONN_STR = System.Configuration.ConfigurationSettings.AppSettings["CONN_STRING"];

    #region ExecuteNonQuery(SQL语句)
    /// <summary>
    /// 执行Update,delete,insert语句
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>

    public static int ExcectueNonQuery(string strSql)
    {

        using (SqlConnection con = new SqlConnection(CONN_STR))
        {
            con.Open();
            SqlCommand command = new SqlCommand(strSql, con);
            try
            {
                return command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
    #endregion

    #region  ExecuteDataset:返回DataSet(查询SQL语句)
    /// <summary>
    /// 执行查询传入Select语句 返回DataSet
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    public static DataSet ExecuteDataset(string strSql)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(CONN_STR))
            {
                conn.Open();
                // System.Data.SqlServerCe.SqlCeCommand com = new SqlCeCommand(strSql, DAL.CreateConn.GetConn());
                SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
                System.Data.DataSet ds = new DataSet();
                da.Fill(ds);
                return ds;
            }
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
    }
    #endregion

    #region  ExecuteObj:传入Sql语句返回首行首列的对象(SQL语句)
    /// <summary>
    /// 传入Sql语句返回首行首列的对象
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    public static object ExecuteObj(string strSql)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(CONN_STR))
            {
                conn.Open();
                SqlCommand command = new SqlCommand(strSql, conn);
                object obj = command.ExecuteScalar();
                if (object.Equals(obj, null))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }

        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
    }
    #endregion
}