数据库常用方法的使用,有了它,数据库访问会变得超级简单,安全问题就要遭高手了。这个复制,黏贴就可以用了,前提是自己配置好数据库。
public class DatabaseHelp
{
public static string connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
public DatabaseHelp()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
#region 执行不返回数据集的的SQL语句,主要用于插入删除时,成功返回值为1,失败返回值为0
public static int Excultesql(string sqlstr)
{
int result = 0;
SqlConnection con = new SqlConnection(DatabaseHelp.connection);
SqlCommand cmd = new SqlCommand(sqlstr, con);
try
{
con.Open();
result = (int)cmd.ExecuteNonQuery();
return result;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
con.Dispose();
con.Close();
}
}
#endregion
#region 利用reader对象对数据库进行查询
public static SqlDataReader readerdata(string sqlstr)
{
SqlConnection con = new SqlConnection(DatabaseHelp.connection);
SqlCommand cmd = new SqlCommand(sqlstr, con);
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
return reader;
}
catch (SqlException ex)
{
throw (ex);
}
finally
{
cmd.Dispose();
con.Close();
}
}
#endregion
#region 利用dataset返回数据表的内容
public static DataSet datasetdata(string sqlstr)
{
SqlConnection con = new SqlConnection(DatabaseHelp.connection);
try
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(sqlstr, con);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
catch (SqlException ex)
{
throw (ex);
}
finally
{
con.Close();
}
}
#endregion
#region 利用ExecuteScalar方法对查询数据进行判断
public static int excuteS(string sqlstr)
{
SqlConnection con=new SqlConnection(DatabaseHelp.connection);
SqlCommand cmd = new SqlCommand(sqlstr, con);
try
{
con.Open();
int result = (int)cmd.ExecuteScalar();
return result;
}
catch (SqlException ex)
{
throw (ex);
}
finally
{
cmd.Dispose();
con.Close();
}
}
#endregion
}