ASP.net的方法解释
发布网友
发布时间:2022-05-14 08:58
我来回答
共1个回答
热心网友
时间:2023-10-12 08:22
string conStr = ConfigurationManager.ConnectionStrings["connectionStr"].ConnectionString;//获得web.config里的连接数据库字符串
SqlConnection cn;
public SqlConnection GetConnection()//获得数据库连接并打开
{
if (cn == null)
{
cn = new SqlConnection(conStr);
cn.Open();
}
else if (cn.State == ConnectionState.Broken || cn.State == ConnectionState.Closed)
{
cn.Open();
}
return cn;
}
public SqlDataReader GetReader(string sql)//根据sql语句获得reader
{
SqlCommand cmd = new SqlCommand(sql, GetConnection());
return cmd.ExecuteReader();
}
public SqlDataReader GetReader(string sql, SqlParameter[] par)
{
SqlCommand cmd = new SqlCommand(sql, GetConnection());
cmd.Parameters.AddRange(par);
return cmd.ExecuteReader();
}
public DataTable GetDataTable(string sql)//根据sql获取DataTable
{
DataTable table = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(sql, GetConnection());
adp.Fill(table);
return table;
}
public int ExecuteSql(string sql)//执行sql语句
{
SqlCommand cmd = new SqlCommand(sql, GetConnection());
return cmd.ExecuteNonQuery();
}
public int ExecuteSql(string sql, SqlParameter[] par)//执行sql语句
{
SqlCommand cmd = new SqlCommand(sql, GetConnection());
cmd.Parameters.AddRange(par);
return cmd.ExecuteNonQuery();
}
public DataSet GetDataSet(string sql, SqlParameter[] sp)//根据sql获取DataSet
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql, GetConnection());
cmd.Parameters.AddRange(sp);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
return ds;
}
public int ExecuteScalar(string sql, SqlParameter[] sp)
{
SqlCommand cmd = new SqlCommand(sql, GetConnection());
cmd.Parameters.AddRange(sp);
int bo = Int32.Parse(cmd.ExecuteScalar().ToString());
return bo;
}
public object GetScalar(string sql)
{
SqlCommand cmd = new SqlCommand(sql, GetConnection());
return cmd.ExecuteScalar();
}
建议楼主学习一下ado.net的几个对象