public static class DBHelper
{
private static SqlConnection connection; //定义连接
public static SqlConnection Connection //打开连接
{
get
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
if (connection == null)
{
connection = new SqlConnection(connectionString);
}
else if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
else if (connection.State == ConnectionState.Broken)
{
connection.Close();
connection.Open();
}
return connection;
}
}
//不带参数的执行命令
public static int ExecuteCommand(string sql)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
return cmd.ExecuteNonQuery();
connection.Close();
}
//带参数的执行命令
public static int ExecuteCommand(string sql, params SqlParameter[] values)
{
SqlCommand cmd = new SqlCommand(sql,Connection);
cmd.Parameters.AddRange(values);
return cmd.ExecuteNonQuery();
connection.Close();
}
//不带参数,执行受影响行数
public static int GetScalar(string sql)
{
SqlCommand cmd = new SqlCommand(sql,Connection);
return Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();
}
//带参数,执行受影响的行数
public static int GetScalar(string sql, params SqlParameter[] values)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
cmd.Parameters.AddRange(values);
return Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();
}
//不带参数,向前式读取数据库
public static SqlDataReader GetReader(string sql)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
SqlDataReader reader = cmd.ExecuteReader();
return reader;
connection.Close();
}
//带参数,向前式读取数据库
public static SqlDataReader GetReader(string sql,params SqlParameter[] values)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
cmd.Parameters.AddRange(values);
SqlDataReader reader = cmd.ExecuteReader();
return reader;
connection.Close();
}
public static DataTable GetDataSet(string sql)
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql,Connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds.Tables[0];
}
public static DataTable GetDataSet(string sql,params SqlParameter[] values)
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql, Connection);
cmd.Parameters.AddRange(values);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds.Tables[0];
}
}
}