C# → 数据库

  Database:
public static class dbconnection{
static string cons = "data source = (local) ;initial catalog = RentManage;integrated security = true;";
static SqlConnection con = null;
public static SqlCommand dbconn(string sql, params SqlParameter[] pms)
{/*连接方法*/
try{
con = new SqlConnection(cons);con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
if (pms != null){ cmd.Parameters.AddRange(pms); }
return cmd;
}catch {return null; }
}
public static int ExecuteNonQuery(string sql, params SqlParameter[] pms)
{//与执行相关
SqlCommand cmd = dbconn(sql, pms);
if (cmd != null){
try{ return cmd.ExecuteNonQuery(); }
catch{ return -;//-1错误码是未查到结果
}finally{ if (con != null) con.Close(); }
}return -;
}
public static object ExecuteScalar(string sql, params SqlParameter[] pms)
{/*登录*/
object obj = -;//-2错误码是未连接成功
SqlCommand cmd = dbconn(sql, pms);
if (cmd != null){
try{ obj = cmd.ExecuteScalar();
}catch{ obj = -;//-1错误码是未查到结果
}finally{ if (con != null) con.Close(); }
}return obj;
}
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pms)
{ //把查询到的数据填充到表格里
try{
con = new SqlConnection(cons);
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
if (pms != null){
adapter.SelectCommand.Parameters.AddRange(pms);
}
DataSet dataset = new DataSet();
adapter.Fill(dataset);
return dataset.Tables[];
}catch (Exception exp){ throw exp;
}finally{ if (con != null) con.Close(); }
}
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)
{//读取查询的信息
SqlCommand cmd = dbconn(sql, pms);
if (cmd != null){
try{
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}catch (Exception exp){
if (con != null){ con.Close(); }
throw exp;
}
}return null;
}
上一篇:Oracle执行计划


下一篇:@Async异步注解与SpringBoot结合使用