简单的DBHelper类

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Configuration;
  6 using System.Data.SqlClient;
  7 using System.Data;//using: 引入命名空间
  8 
  9 namespace DBHelper
 10 {
 11     public static class DBHelper
 12     {
 13         //Web.config 配置
 14         // <?xml version="1.0"?>
 15         //
 16         //    <configuration>
 17         //
 18         //        <!--指定配置节和命名空间声明。clear:移除对继承的节和节组的所有引用,只允许由当前 section 和 sectionGroup 元素添加的节和节组。remove:移除对继承的节和节组的引用。section:定义配置节处理程序与配置元素之间的关联。sectionGroup:定义配置节处理程序与配置节之间的关联。-->
 19         //      <configSections>
 20         //        ............
 21         //      </configSections>
 22         //
 23         //      <!--appSettings是应用程序设置,可以定义应用程序的全局常量设置等信息-->
 24         //      <appSettings>
 25         //            ..............
 26         //     </appSettings>
 27         //
 28         //     <!--连接字符串设置-->
 29         //      <connectionStrings>
 30         //        <add name="strCon" connectionString="Data Source=CUSTDB;user=HISSG_AG;password=HISSG_AG;"/>
 31         //      </connectionStrings>
 32         //
 33         //      <system.web>
 34               
 35         //      </system.web>
 36         //      .................
 37         //      .................
 38         //    </configuration>
 39 
 40 
 41         //要引入using System.Configuration命名空间
 42         private static readonly string connectionString = ConfigurationManager.ConnectionStrings["strCon"].ConnectionString;
 43 
 44         /// <summary>
 45         ///  执行SQL语句,返回受影响的行数(用于insert,delete,update等)
 46         /// </summary>
 47         /// <param name="strSQL">SQL语句</param>
 48         /// <returns>受影响的行数</returns>
 49         public static int ExecuteSql(string strSQL)
 50         {
 51             //using: 释放资源
 52             //SqlConnection: 连接数据源
 53             //connectionString:用于连接数据源的字符串
 54             using (SqlConnection conn = new SqlConnection(connectionString))
 55             {
 56                 //SqlCommand对数据源执行SQl命令
 57                 //SqlCommand(CommandText, CommandString):strSQL需执行的SQL命令字符串,conn指定执行SQL命令需连接的数据源
 58                 using (SqlCommand cmd = new SqlCommand(strSQL, conn))
 59                 {
 60                     try
 61                     {
 62                         conn.Open();//打开数据源连接
 63                         int rows = cmd.ExecuteNonQuery();//执行SQL语句,返回受影响的行数。如rows>0,说明执行成功
 64                         return rows;
 65                     }
 66                     catch (System.Data.SqlClient.SqlException e)
 67                     {
 68                         conn.Close();//出异常,关闭数据源连接
 69                         throw e;
 70                     }
 71                 }
 72             }
 73         }
 74 
 75         /// <summary>
 76         /// 执行带参数的非查询SQL
 77         /// </summary>
 78         /// <param name="strSQL">SQL语句</param>
 79         /// <param name="values">参数</param>
 80         /// <returns>受影响行数</returns>
 81         public static int ExecuteCommand(string strSQL, params SqlParameter[] values)
 82         {
 83             using (SqlConnection conn = new SqlConnection(connectionString))
 84             {
 85                 using (SqlCommand cmd = new SqlCommand(strSQL, conn))
 86                 {
 87                     try
 88                     {
 89                         conn.Open();//打开数据源连接
 90                         cmd.Parameters.AddRange(values);
 91                         int rows = cmd.ExecuteNonQuery();//执行SQL语句,返回受影响的行数。如rows>0,说明执行成功
 92                         return rows;
 93                     }
 94                     catch (System.Data.SqlClient.SqlException ex)
 95                     {
 96                         conn.Close();//出异常,关闭数据源连接
 97                         throw new Exception(string.Format("执行{0}失败:{1}", strSQL, ex.Message));
 98                     }
 99                 }
100             }
101         }
102 
103         /// <summary>
104         ///  执行查询SQL语句,返回SqlDataReader(只进记录集) ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
105         /// </summary>
106         /// <param name="strSQL">查询语句</param>
107         /// <returns>SqlDataReader</returns>
108         public static SqlDataReader ExecuteReader(string strSQL)
109         {
110             using (SqlConnection conn = new SqlConnection(connectionString))
111             {
112                 using (SqlCommand cmd = new SqlCommand(strSQL, conn))
113                 {
114                     try
115                     {
116                         conn.Open();//打开数据源连接
117                         //CommandBehavior.CloseConnection 能够保证当SqlDataReader对象被关闭时,其依赖的连接也会被自动关闭。
118                         SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
119                         return myReader;
120                     }
121                     catch (System.Data.SqlClient.SqlException ex)
122                     {
123                         conn.Close();//出异常,关闭数据源连接
124                         throw new Exception(string.Format("执行{0}失败:{1}", strSQL, ex.Message));
125                     }
126                 }
127             }
128         }
129 
130         /// <summary>
131         ///  执行带参数的查询SQL语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
132         /// </summary>
133         /// <param name="strSQL">查询语句</param>
134         /// <param name="values">参数</param>
135         /// <returns>SqlDataReader</returns>
136         public static SqlDataReader ExecuteReader(string strSQL, params SqlParameter[] values)
137         {
138             using (SqlConnection conn = new SqlConnection(connectionString))
139             {
140                 using (SqlCommand cmd = new SqlCommand(strSQL, conn))
141                 {
142                     try
143                     {
144                         conn.Open();//打开数据源连接
145                         //CommandBehavior.CloseConnection 能够保证当SqlDataReader对象被关闭时,其依赖的连接也会被自动关闭。
146                         cmd.Parameters.AddRange(values);
147                         SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
148                         return myReader;
149                     }
150                     catch (System.Data.SqlClient.SqlException ex)
151                     {
152                         conn.Close();//出异常,关闭数据源连接
153                         throw new Exception(string.Format("执行{0}失败:{1}", strSQL, ex.Message));
154                     }
155                 }
156             }
157         }
158 
159 
160         ///DataReader和DataSet的区别
161         ///1.获取数据的方式:
162         ///    DataReader(在线-一直占用SqlConnection连接,其它操作就可以不可使用,占用内存较小)
163         ///    DataSet(离线-将数据一次性读入内存,然后断开连接,其它操作就可以使用,比较消耗资源)
164         ///2.获取数据的机制
165         ///    DataReader是通过IDbCommand.ExecuteReader来读取数据。
166         ///    DataSet则是通过DbDataAdapter.Fill来填充数据
167         ///3.其它区别
168         ///    DataReader读取速度快于DataSet。
169         ///    DataReader是数据提供者类,DataSet是一般性类,借助于DbDataAdapter来填充数据。
170         ///...............................等
171 
172 
173         /// <summary>
174         ///  执行查询SQL语句,返回离线记录集
175         /// </summary>
176         /// <param name="strSQL">SQL语句</param>
177         /// <returns>离线记录DataSet</returns>
178         public DataSet getDataTablebySQL(string strSQL)
179         {
180             using (SqlConnection conn = new SqlConnection(connectionString))
181             {
182                 using (SqlCommand cmd = new SqlCommand(strSQL, conn))
183                 {
184                     try
185                     {
186                         conn.Open();//打开数据源连接
187                         DataSet ds = new DataSet();
188                         SqlDataAdapter myAdapter = new SqlDataAdapter(cmd);
189                         myAdapter.Fill(ds);
190                         return ds;
191                     }
192                     catch (System.Data.SqlClient.SqlException ex)
193                     {
194                         conn.Close();//出异常,关闭数据源连接
195                         throw new Exception(string.Format("执行{0}失败:{1}", strSQL, ex.Message));
196                     }
197                 }
198             }
199         }
200 
201         /// <summary>
202         ///  执行带参数的查询SQL,返回离线记录集
203         /// </summary>
204         /// <param name="strSQL"></param>
205         /// <returns></returns>
206         public DataSet getDataTablebySQL(string strSQL, params SqlParameter[] values)
207         {
208             using (SqlConnection conn = new SqlConnection(connectionString))
209             {
210                 using (SqlCommand cmd = new SqlCommand(strSQL, conn))
211                 {
212                     try
213                     {
214                         conn.Open();//打开数据源连接
215                         DataSet ds = new DataSet();
216                         cmd.Parameters.AddRange(values);
217                         SqlDataAdapter myAdapter = new SqlDataAdapter(cmd);
218                         myAdapter.Fill(ds);
219                         return ds;
220                     }
221                     catch (System.Data.SqlClient.SqlException ex)
222                     {
223                         conn.Close();//出异常,关闭数据源连接
224                         throw new Exception(string.Format("执行{0}失败:{1}", strSQL, ex.Message));
225                     }
226                 }
227             }
228         }
229 
230         /// <summary>
231         ///  执行查询SQL语句,返回离线记录集
232         /// </summary>
233         /// <param name="strSQL">SQL语句</param>
234         /// <returns>离线记录DataSet</returns>
235         public DataTable getDataTablebySQL(string strSQL)
236         {
237             using (SqlConnection conn = new SqlConnection(connectionString))
238             {
239                 using (SqlCommand cmd = new SqlCommand(strSQL, conn))
240                 {
241                     try
242                     {
243                         conn.Open();//打开数据源连接
244                         DataSet ds = new DataSet();
245                         SqlDataAdapter myAdapter = new SqlDataAdapter(cmd);
246                         myAdapter.Fill(ds);
247                         return ds.Tables[0];
248                     }
249                     catch (System.Data.SqlClient.SqlException ex)
250                     {
251                         conn.Close();//出异常,关闭数据源连接
252                         throw new Exception(string.Format("执行{0}失败:{1}", strSQL, ex.Message));
253                     }
254                 }
255             }
256         }
257 
258         /// <summary>
259         ///  执行带参数的查询SQL,返回离线记录集
260         /// </summary>
261         /// <param name="strSQL"></param>
262         /// <returns></returns>
263         public DataTable getDataTablebySQL(string strSQL,params SqlParameter[] values)
264         {
265             using (SqlConnection conn = new SqlConnection(connectionString))
266             {
267                 using (SqlCommand cmd = new SqlCommand(strSQL, conn))
268                 {
269                     try
270                     {
271                         conn.Open();//打开数据源连接
272                         DataSet ds = new DataSet();
273                         cmd.Parameters.AddRange(values);
274                         SqlDataAdapter myAdapter = new SqlDataAdapter(cmd);
275                         myAdapter.Fill(ds);
276                         return ds.Tables[0];
277                     }
278                     catch (System.Data.SqlClient.SqlException ex)
279                     {
280                         conn.Close();//出异常,关闭数据源连接
281                         throw new Exception(string.Format("执行{0}失败:{1}", strSQL, ex.Message));
282                     }
283                 }
284             }
285         }
286     }
287 }

 

转载于:https://www.cnblogs.com/qzyStar/p/4552104.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
DBHelper通常用于数据库的操作,包括增删改查等。以下是一个简单DBHelper的示例代码,可以实现基本的增删改查操作。 ```java public class DBHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "mydb.db"; private static final int DATABASE_VERSION = 1; public static final String TABLE_NAME = "mytable"; public static final String COL_ID = "id"; public static final String COL_NAME = "name"; public static final String COL_AGE = "age"; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE " + TABLE_NAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_NAME + " TEXT, " + COL_AGE + " INTEGER)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "DROP TABLE IF EXISTS " + TABLE_NAME; db.execSQL(sql); onCreate(db); } public void insert(String name, int age) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COL_NAME, name); values.put(COL_AGE, age); db.insert(TABLE_NAME, null, values); db.close(); } public void delete(int id) { SQLiteDatabase db = this.getWritableDatabase(); String whereClause = COL_ID + " = ?"; String[] whereArgs = {String.valueOf(id)}; db.delete(TABLE_NAME, whereClause, whereArgs); db.close(); } public void update(int id, String name, int age) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COL_NAME, name); values.put(COL_AGE, age); String whereClause = COL_ID + " = ?"; String[] whereArgs = {String.valueOf(id)}; db.update(TABLE_NAME, values, whereClause, whereArgs); db.close(); } public List<Person> query() { List<Person> list = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); String[] columns = {COL_ID, COL_NAME, COL_AGE}; Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex(COL_ID)); String name = cursor.getString(cursor.getColumnIndex(COL_NAME)); int age = cursor.getInt(cursor.getColumnIndex(COL_AGE)); Person person = new Person(id, name, age); list.add(person); } cursor.close(); db.close(); return list; } } ``` 其中,Person是一个简单的Java,用于保存查询结果。 ```java public class Person { private int id; private String name; private int age; public Person(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public String getName() { return name; } public int getAge() { return age; } } ``` 使用DBHelper进行增删改查操作的示例代码: ```java DBHelper dbHelper = new DBHelper(context); // 插入数据 dbHelper.insert("张三", 18); // 删除数据 dbHelper.delete(1); // 更新数据 dbHelper.update(2, "李四", 20); // 查询数据 List<Person> list = dbHelper.query(); for (Person person : list) { Log.d("DBHelper", person.getId() + " " + person.getName() + " " + person.getAge()); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值