C# 通用数据访问类
一、原始方法
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace SaiAo.UI.Helper { public class SqlHelper { private static readonly string connString = ConfigurationManager.ConnectionStrings["connString"].ToString(); /// <summary> /// 执行增删改的方法 /// </summary> /// <param name="sql"></param> /// <returns></returns> public static int Update(string sql) { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql, conn); try { conn.Open(); return cmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { conn.Close(); } } /// <summary> /// 结果集中的第一行的第一列 /// </summary> /// <param name="sql"></param> /// <returns></returns> public static object Update1(string sql) { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql, conn); try { conn.Open(); return cmd.ExecuteScalar(); } catch (Exception ex) { throw ex; } finally { conn.Close(); } } /// <summary> /// 执行一个结果集的查询 /// </summary> /// <param name="sql"></param> /// <returns></returns> public static SqlDataReader GetReader(string sql) { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql, conn); try { conn.Open(); return cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { conn.Close(); throw ex; } } } }
调用:
public void Test() { string sql = "select AdminName,* from user where usercode={0}"; sql = string.Format(sql,"admin"); try { SqlDataReader objReader = SqlHelper.GetReader(sql); if (objReader.Read()) { //取值 objReader["AdminName"].ToString(); objReader.Close(); } } catch (Exception ex) { throw new Exception("应用程序或数据库出现错误"+ex.Message); } }
二、
作者:chenze 出处:https://www.cnblogs.com/chenze-Index/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |