C#-SQLHelper
关于SQLHelper,没有什么太大的难度,但是,隔一段时间不写,难免会忘记,下面将代码贴上,供大家分享。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace ItcastSIM.DAL
{
public class SQLHelper
{
private static readonly string conStr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
public static SqlDataReader ExecuteReader(string sql, CommandType type, params SqlParameter[] param)
{
SqlDataReader dataReader = new SqlDataReader();
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = type;
cmd.Parameters.AddRange(param);
dataReader = cmd.ExecuteReader();
}
}
return dataReader;
}
public static DataTable GetTable(string sql, CommandType type, params SqlParameter[] param)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = type;
cmd.Parameters.AddRange(param);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
}
return dt;
}
public static int ExecuteNonQuery(string sql, CommandType type, params SqlParameter[] param)
{
int r = -1;
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = type;
cmd.Parameters.AddRange(param);
con.Open();
r = cmd.ExecuteNonQuery();
}
}
return r;
}
public static object ExecuteScalar(string sql, CommandType type, params SqlParameter[] param)
{
object o = null;
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = type;
cmd.Parameters.AddRange(param);
con.Open();
o = cmd.ExecuteScalar();
}
}
return o;
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。