SqlHelper 简单版

时间:2014-05-20 10:08:21   收藏:0   阅读:328
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace AddressBook
{
    class SqlHelper
    {
        /// <summary>
        /// 连接数据库的字符串
        /// </summary>
        private static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;

        /// <summary>
        /// 返回一个DataTable结果集
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="sqlParameter">sql语句中的参数</param>
        /// <returns>DataTable</returns>
        public static DataTable ExecuteDataTable(string sql, params SqlParameter[] sqlParameter)
        {
            DataSet ds = new DataSet(); //创建一个表在内存里
            //创建适配器对象
            SqlDataAdapter adapter = new SqlDataAdapter(sql, connectionString);
            //添加参数到Adapter的selectCommand命令中
            adapter.SelectCommand.Parameters.AddRange(sqlParameter);
            try
            {
                adapter.Fill(ds); //填充ds
                return ds.Tables[0];//返回ds数据集中第一个表
            }
            catch
            {
                return null;
            }
            finally
            {
                adapter.Dispose(); //清理资源
            }
        }


        /// <summary>
        /// 返回增/删/改 受影响的行数
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="sqlParameter">sql语句中的参数</param>
        /// <returns>int</returns>
        public static int ExecuteNonQuery(string sql, params SqlParameter[] sqlParameter)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(sqlParameter);
                    conn.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// 返回查询的首行首列
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="sqlParameter">sql语句中的参数</param>
        /// <returns></returns>
        public static object ExecuteScalar(string sql, params SqlParameter[] sqlParameter)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(sqlParameter);
                    conn.Open();
                    return cmd.ExecuteScalar();
                }
            }
        }

    }
}
bubuko.com,布布扣

 

SqlHelper 简单版,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!