C# → 数据库

 1  Database:
 2 public static class dbconnection{
 3         static string cons = "data source = (local) ;initial catalog = RentManage;integrated security = true;";
 4         static SqlConnection con = null;
 5         public static SqlCommand dbconn(string sql, params SqlParameter[] pms)
 6         {/*连接方法*/
 7             try{
 8                 con = new SqlConnection(cons);con.Open();
 9                 SqlCommand cmd = new SqlCommand(sql, con);
10                 if (pms != null){ cmd.Parameters.AddRange(pms); }
11                 return cmd;
12             }catch {return null; }
13         }
14         public static int ExecuteNonQuery(string sql, params SqlParameter[] pms)
15         {//与执行相关
16             SqlCommand cmd = dbconn(sql, pms);
17             if (cmd != null){
18                 try{ return cmd.ExecuteNonQuery(); }
19 catch{ return -1;//-1错误码是未查到结果
20                 }finally{ if (con != null) con.Close(); }
21             }return -2;
22         }
23         public static object ExecuteScalar(string sql, params SqlParameter[] pms)
24         {/*登录*/
25             object obj = -2;//-2错误码是未连接成功
26             SqlCommand cmd = dbconn(sql, pms);
27             if (cmd != null){
28                 try{ obj = cmd.ExecuteScalar();
29                 }catch{ obj = -1;//-1错误码是未查到结果
30                 }finally{ if (con != null) con.Close(); }
31             }return obj;
32         }
33         public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pms)
34         { //把查询到的数据填充到表格里
35             try{
36                 con = new SqlConnection(cons);
37                 SqlCommand cmd = new SqlCommand(sql, con);
38                 SqlDataAdapter adapter = new SqlDataAdapter(cmd);
39                 if (pms != null){
40                     adapter.SelectCommand.Parameters.AddRange(pms);
41                 }
42                 DataSet dataset = new DataSet();
43                 adapter.Fill(dataset);
44                 return dataset.Tables[0];
45             }catch (Exception exp){ throw exp;
46             }finally{ if (con != null) con.Close(); }
47         }
48         public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)
49         {//读取查询的信息
50             SqlCommand cmd = dbconn(sql, pms);
51             if (cmd != null){
52                 try{
53                     return cmd.ExecuteReader(CommandBehavior.CloseConnection);
54                 }catch (Exception exp){
55                     if (con != null){ con.Close();  }
56                     throw exp;
57                 }
58             }return null;
59         }

 

posted @ 2019-03-04 22:47  MoonTwilight  阅读(348)  评论(0编辑  收藏  举报