下面这段代码实现一个ASP.NET数据库驱动类:DBHelper。
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Data;
- using System.Data.SqlClient;
- namespace DBUtility
- {
- public static class SQLHelper
- {
- private static string connectionString =
- @"server=.\SQLEXPRESS;uid=sa;pwd=;database=MyBookShop";
- private static SqlConnection sqlConn;
- /// < summary>
- ///
- /// < /summary>
- /// < param name="sql">< /param>
- /// < returns>< /returns>
- public static SqlDataReader GetDataReader(string sql)
- {
- try
- {
- sqlConn = new SqlConnection(connectionString);
- sqlConn.Open();
- SqlCommand sqlCmd = new SqlCommand(sql,sqlConn);
- SqlDataReader sqlDr =
- sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
- return sqlDr;
- }
- catch (SqlException ex)
- {
- throw ex;
- }
- }
- public static object ExecScalar(string sql)
- {
- try
- {
- sqlConn = new SqlConnection(connectionString);
- sqlConn.Open();
- SqlCommand sqlCmd = new SqlCommand(sql, sqlConn);
- object obj =
- sqlCmd.ExecuteScalar();
- return obj;
- }
- catch (SqlException ex)
- {
- throw ex;
- }
- finally
- {
- sqlConn.Close();
- }
- }
- /// < summary>
- /// ASP.NET数据库驱动类:执行带参的命令式的存储过程
- /// < /summary>
- /// < param name="procName">存储过程名称< /param>
- /// < param name="paras">为存储过程的参数解决赋参的SqlParameter对象数组
- /// (每一个SqlParameter对象为一个参数解决赋参)< /param>
- /// < returns>存储过程的返回值< /returns>
- public static int ExecuteProc1(string procName,
- SqlParameter[] paras)
- {
- try
- {
- sqlConn = new SqlConnection(connectionString);
- sqlConn.Open();
- SqlCommand sqlCmd = new SqlCommand(procName, sqlConn);
- //执行存储过程类型
- sqlCmd.CommandType = CommandType.StoredProcedure;
- sqlCmd.Parameters.AddRange(paras);
- SqlParameter p = new SqlParameter();
- //取存储过程的返回值
- p.Direction = ParameterDirection.ReturnValue;
- p.SqlDbType = SqlDbType.Int;
- sqlCmd.Parameters.Add(p);
- sqlCmd.ExecuteNonQuery();
- int v = p.Value==null?-1:Convert.ToInt32(p.Value);
- return v;
- }
- catch (SqlException ex)
- {
- throw ex;
- }
- finally
- {
- sqlConn.Close();
- }
- }
- /// < summary>
- /// ASP.NET数据库驱动类:执行带参的查询式的存储过程
- /// < /summary>
- /// < param name="procName">存储过程名称< /param>
- /// < param name="paras">为存储过程的参数解决赋参的SqlParameter对象数组
- /// (每一个SqlParameter对象为一个参数解决赋参)< /param>
- /// < returns>存储过程执行完毕后如果在数据库服务器端形成一个
- /// 查询结果集,则返回指向该结果集的一个数据读取器对象< /returns>
- public static SqlDataReader ExecuteProc2(string procName,
- SqlParameter[] paras)
- {
- try
- {
- sqlConn = new SqlConnection(connectionString);
- sqlConn.Open();
- SqlCommand sqlCmd = new SqlCommand(procName, sqlConn);
- //执行存储过程类型
- sqlCmd.CommandType = CommandType.StoredProcedure;
- sqlCmd.Parameters.AddRange(paras);
- SqlDataReader sqlDr =
- sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
- return sqlDr;
- }
- catch (SqlException ex)
- {
- throw ex;
- }
- }
- }
- }
以上就是ASP.NET数据库驱动类DBHelper的实现代码。
【编辑推荐】