public class SQLHelper
{
public static string _con = ConfigurationManager.ConnectionStrings["zh"].ConnectionString;
public static bool Execute(string sql)
{
SqlConnection conn = new SqlConnection(_con);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (SqlException e)
{
conn.Close();
throw new Exception(e.Message);
}
finally
{
cmd.Dispose();
conn.Close();
}
}
public static DataSet Query(string sql)
{
SqlConnection conn = new SqlConnection(_con);
DataSet ds = new DataSet();
try
{
conn.Open();
SqlDataAdapter command = new SqlDataAdapter(sql, conn);
command.Fill(ds, "ds");
conn.Close();
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
/// <summary>
/// 执行查询语句,返回SqlDataReader(使用该方法切记要手工关闭SqlDataReader和连接)
/// </summary>
/// <param name="sql">查询语句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string sql)
{
SqlConnection conn = new SqlConnection(_con);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (SqlException e)
{
throw new Exception(e.Message);
}
//finally //不能在此关闭,否则,返回的对象将无法使用
//{
// cmd.Dispose();
// connection.Close();
//}
}
}