ASP.NET----表格使用与数据绑定好用的sqlCommon基类

  1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Data.SqlClient;
6 using System.Configuration;
7 using System.Data;
8
9 namespace TestDataGriv
10 {
11 public class sqlCommon
12 {
13 private static SqlConnection conn = new SqlConnection();
14 private static SqlCommand comm = new SqlCommand();
15
16 public sqlCommon()
17 {
18
19 }
20
21 /// <summary>
22 /// 打开连接
23 /// </summary>
24 private static void openConnection()
25 {
26 if (conn.State == ConnectionState.Closed)
27 {
28 try
29 {
30 conn.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
31 comm.Connection = conn;
32 conn.Open();
33 }
34 catch (Exception e)
35 {
36 throw new Exception(e.Message);
37 }
38 }
39 }
40 /// <summary>
41 /// 关闭连接
42 /// </summary>
43 private static void closeConnection()
44 {
45 if (conn.State == ConnectionState.Open)
46 {
47 conn.Close();
48 }
49 conn.Dispose();
50 comm.Dispose();
51 }
52 /// <summary>
53 /// 执行一条sql语句
54 /// </summary>
55 /// <param name="sqlStr">sql语句</param>
56 public static void ExecuteSql(string sqlStr)
57 {
58 try
59 {
60 openConnection();
61 comm.CommandType = CommandType.Text;
62 comm.CommandText = sqlStr;
63 comm.ExecuteNonQuery();
64 }
65 catch (Exception e)
66 {
67 throw new Exception(e.Message);
68 }
69 finally
70 {
71 closeConnection();
72 }
73 }
74 /// <summary>
75 /// 返回一个数据集
76 /// </summary>
77 /// <param name="sqlStr">sql语句</param>
78 /// <returns></returns>
79 public static DataSet dataSet(string sqlStr)
80 {
81 SqlDataAdapter da = new SqlDataAdapter();
82 DataSet ds = new DataSet();
83 try
84 {
85 openConnection();
86 comm.CommandType = CommandType.Text;
87 comm.CommandText = sqlStr;
88 da.SelectCommand = comm;
89 da.Fill(ds);
90 }
91 catch (Exception e)
92 {
93 throw new Exception(e.Message);
94 }
95 finally
96 {
97 closeConnection();
98 }
99 return ds;
100 }
101
102 /// <summary>
103 /// 返回一个数据视图
104 /// </summary>
105 /// <param name="sqlStr">sql语句</param>
106 /// <returns></returns>
107 public static DataView dataView(string sqlStr)
108 {
109 SqlDataAdapter da = new SqlDataAdapter();
110 DataView dv = new DataView();
111 DataSet ds = new DataSet();
112 try
113 {
114 openConnection();
115 comm.CommandType = CommandType.Text;
116 comm.CommandText = sqlStr;
117 da.SelectCommand = comm;
118 da.Fill(ds);
119 dv = ds.Tables[0].DefaultView;
120 }
121 catch (Exception e)
122 {
123 throw new Exception(e.Message);
124 }
125 finally
126 {
127 closeConnection();
128 }
129 return dv;
130 }
131 }
132 }

  

posted @ 2011-09-06 15:03  brainmao  阅读(681)  评论(0编辑  收藏  举报