首页 > 代码库 > SqlHelper
SqlHelper
自己写的一个SqlHelper:
namespace SQLHelper
{
class SqlHelper
{
private static string Connstr = ConfigurationManager.ConnectionStrings["dbConnStr"].ConnectionString;
#region 第一版
//public static int ExecuteNonQuery(string sql)
//{
// using (SqlConnection conn = new SqlConnection(Connstr))
// {
// conn.Open();
// using (SqlCommand cmd = conn.CreateCommand())
// {
// cmd.CommandText = sql;
// return cmd.ExecuteNonQuery();
// }
// }
//}
//public static object ExecuteScalar(string sql)
//{
// using (SqlConnection conn = new SqlConnection(Connstr))
// {
// conn.Open();
// using (SqlCommand cmd = conn.CreateCommand())
// {
// cmd.CommandText = sql;
// return cmd.ExecuteScalar();
// }
// }
//}
//public static DataTable ExecuteDataTable(string sql)
//{
// using (SqlConnection conn = new SqlConnection(Connstr))
// {
// conn.Open();
// using (SqlCommand cmd = conn.CreateCommand())
// {
// cmd.CommandText = sql;
// SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// DataSet dataset = new DataSet();
// adapter.Fill(dataset);
// return dataset.Tables[0];
// }
// }
//}
#endregion
//将参数传进去且设为长度可变参数
public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(Connstr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteNonQuery();
}
}
}
public static object ExecuteScalar(string sql,params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(Connstr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteScalar();
}
}
}
public static DataTable ExecuteDataTable(string sql ,params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(Connstr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
return dataset.Tables[0];
}
}
}
}
}
SqlHelper