using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace MyBookShop.DAL
{
public static class DBHelper
{
private static string connstring = ConfigurationManager.ConnectionStrings["sqlstring"].ConnectionString;
//执行的方法,sql不带参的最适用于删除
public static int ExecteCommand(string sql)
{
SqlConnection con = new SqlConnection(connstring);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
int result = cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
return result;
}
//执行的方法,sql带参
public static int ExecuteCommand(string sql,params SqlParameter [] pa)
{
SqlConnection con = new SqlConnection(connstring);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
if (pa!=null)
{
cmd.Parameters.AddRange(pa);
}
int result = cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
return result;
}
//执行查询,用dataset返回 sql语句不带参数
public static DataTable GetDataSet(string sql)
{
SqlConnection con = new SqlConnection(connstring);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.Dispose();
con.Close();
return ds.Tables[0];
}
//执行查询,用dataset返回 sql语句带参数
public static DataTable GetDataSet(string sql,params SqlParameter[] pa)
{
SqlConnection con = new SqlConnection(connstring);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
if (pa!=null)
{
cmd.Parameters.AddRange(pa);
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.Dispose();
con.Close();
return ds.Tables[0];
}
//执行查询,用sqldatareader返回
public static SqlDataReader GetReader(string sql)
{
SqlConnection con = new SqlConnection(connstring);
con.Open();
SqlCommand cmd = new SqlCommand(sql,con);
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return dr;
}
//执行查询,用sqldatareader返回,sql语句带参数
public static SqlDataReader GetReader(string sql,params SqlParameter [] pa)
{
SqlConnection con = new SqlConnection(connstring);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
if (pa!=null)
{
cmd.Parameters.AddRange(pa);
}
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return dr;
}
//返回最新插入表的自增长列,sql语句不带参数
public static int GetScalar(string sql)
{
SqlConnection con = new SqlConnection(connstring);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
int result = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
con.Close();
return result;
}
//返回最新插入表的自增长列,sql语句不带参数
public static int GetScalar(string sql,params SqlParameter[] pa)
{
SqlConnection con = new SqlConnection(connstring);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
if (pa!=null)
{
cmd.Parameters.AddRange(pa);
}
int result = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
con.Close();
return result;
}