1、【在web.config文件中配置】
2、【连接字符串】
private static readonly string StrCon = ConfigurationManager.ConnectionStrings["sqlConnection"].ToString();
3、【查询数据方法】
///
/// 查询数据
///
/// 查询语句
/// 参数
///
public static DataTable QueryData(string sqlStr,params SqlParameter [] parameter) {
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
DataSet dt = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
cmd.Parameters.AddRange(parameter);
adapter.SelectCommand = cmd;
adapter.Fill(dt);
conn.Close();
return dt.Tables[0];
}
}
catch (Exception ex)
{
throw new ApplicationException("查询数据异常"+ex.Message);
}
}
4、【更新数据方法】
///
/// 更新数据
///
/// 更新语句
/// 参数
///
public static bool UpdateData(string sqlStr, params SqlParameter[] parameter) {
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr,conn);
cmd.Parameters.AddRange(parameter);
var row=cmd.ExecuteNonQuery();
conn.Close();
if (row>0)
{
return true;
}
return false;
}
}
catch (Exception ex)
{
throw new ApplicationException("更新数据异常"+ex.Message) ;
}
}
5、【删除数据方法】
///
/// 删除数据
///
/// 删除语句
/// 参数
///
public static bool DeleteData(string sqlStr,params SqlParameter[] parameter) {
try
{
using (SqlConnection conn=new SqlConnection())
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr,conn);
cmd.Parameters.AddRange(parameter);
var row = cmd.ExecuteNonQuery();
conn.Close();
if (row>0)
{
return true;
}
return false;
}
}
catch (Exception ex)
{
throw new ApplicationException("删除数据异常"+ex.Message);
}
}
6、【添加数据方法】
///
/// 删除数据
///
/// 删除语句
/// 参数
///
public static bool AddData(string sqlStr,params SqlParameter[] parameter) {
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr,conn);
cmd.Parameters.AddRange(parameter);
var row = cmd.ExecuteNonQuery();
conn.Close();
if (row>0)
{
return true;
}
return false;
}
}
catch (Exception ex)
{
throw new ApplicationException("添加数据异常"+ex.Message);
}
}
7、写个方法调用【查询数据方法】,其他三个方法调用与此类似
public DataTable GetInfo(string id) {
var sqlStr = "select * from Student where id=@id";
DataTable table = SqlHelper.QueryData(sqlStr, new System.Data.SqlClient.SqlParameter[] { new System.Data.SqlClient.SqlParameter("@id",id) });
return table;
}