<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>
/// Obtain the data connection string
/// </Summary>
/// <Returns> </returns>
Public static string GetConnectionString ()
{
Return ConfigurationManager. ConnectionStrings ["ASPNET3_5_DataBase"]. ConnectionString;
}
/// <Summary>
/// Execute the query and return the result to the able
/// </Summary>
/// <Param name = "strSql"> query statement </param>
/// <Param name = "parameters"> possible parameters </param>
/// <Returns> returns a query result table </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>
/// Add, delete, and modify data
/// </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>
/// Execute the query and return the value of the first column in the first row of the result set
/// </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 ();
}
}
}
}
}
From hi_dzj's column