<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace SqlHelper
{
public class SQLHelper
{
/// <summary>
/// 獲取數據連接字符串
/// </summary>
/// <returns></returns>
public static string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["ASPNET3_5_DataBase"].ConnectionString;
}
/// <summary>
/// 執行查詢並將結果返回至DataTable中
/// </summary>
/// <param name="strSql">查詢語句</param>
/// <param name="parameters">可能帶的參數</param>
/// <returns>返回一張查詢結果表</returns>
public static DataTable ExecuteDataTable(string strSql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = strSql;
foreach (SqlParameter p in parameters)
{
cmd.Parameters.Add(p);
}
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
return ds.Tables[0];
}
}
}
}
/// <summary>
/// 執行對數據的增刪改操作
/// </summary>
/// <param name="strSql"></param>
/// <param name="parameters"></param>
public static void ExecuteNonQuery(string strSql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = strSql;
foreach (SqlParameter p in parameters)
{
cmd.Parameters.Add(p);
}
cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// 執行查詢並返回結果集中第一行第一列的值
/// </summary>
/// <param name="strSql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static object ExecuteScalar(string strSql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = strSql;
foreach (SqlParameter p in parameters)
{
cmd.Parameters.Add(p);
}
return cmd.ExecuteScalar();
}
}
}
}
}
摘自 hi_dzj的專欄