链接SQL Server 的DBHelper

public static class DBHelper
{
private static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["PrimeMSSQL"].ConnectionString;

public static int ExecuteCommand(string safeSql)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand(safeSql, connection);
return cmd.ExecuteNonQuery();
}
}

public static int ExecuteCommand(string sql, params SqlParameter[] values)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddRange(values);
return cmd.ExecuteNonQuery();
}
}

public static int GetScalar(string safeSql)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand(safeSql, connection);
return Convert.ToInt32(cmd.ExecuteScalar());
}
}
public static int GetScalar(string sql, params SqlParameter[] values)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddRange(values);
return Convert.ToInt32(cmd.ExecuteScalar());
}
}

public static SqlDataReader GetReader(string safeSql)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand(safeSql, connection);
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}

public static SqlDataReader GetReader(string sql, params SqlParameter[] values)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddRange(values);
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}

public static DataTable GetDataSet(string safeSql)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(safeSql, connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds.Tables[0];
}
}

public static DataTable GetDataSet(string sql, params SqlParameter[] values)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
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];
}
}
}

posted @ 2015-10-23 16:19  情难舍,人难留  阅读(253)  评论(0编辑  收藏  举报