using System.Data;
using System.Data.SqlClient;
namespace SqlHelperNameSpace
{
class SqlHelper
{
private static readonly string ConStr = "Data Source=.;database=mlh;Integrated Security=True";
public static int ExecuteNonQuery(string sql)
{
using (SqlConnection con = new SqlConnection(ConStr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
int a = -1;
a = cmd.ExecuteNonQuery();
con.Close();
return a;
}
}
}
public static int ExecuteScalar(string sql)
{
using (SqlConnection con = new SqlConnection(ConStr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
try
{
return (int)cmd.ExecuteScalar();
}
catch
{
throw;
}
}
}
}
public static SqlDataReader SqlDataReader(string sql)
{
SqlConnection con = new SqlConnection(ConStr);
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
try
{
//关闭reader的同时把数据库连接给关掉
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
catch
{
throw;
}
}
}
public static DataTable SqlDataAdapter(string sql)
{
using (SqlConnection con = new SqlConnection(ConStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
DataSet ds = new DataSet();
try
{
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds, "table");
DataTable dt = ds.Tables["table"];
con.Close();
return dt;
}
catch
{
con.Close();
throw;
}
}
}
}
}
}