namespace ConsoleApplication2
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration; public class SqlHelper
{
/// <summary>
/// 连接字符串
/// </summary>ConfigurationManager.ConnectionStrings["sqlConn"].ConnectionString;
/// <summary>
/// 准备Command对象
/// </summary>
/// <param name="sql"></param>
/// <param name="spms"></param>
/// <returns></returns>
private static SqlCommand PrepareCommand(string sql, params SqlParameter[] spms)
{
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(sql, conn);
if (spms != null)
cmd.Parameters.AddRange(spms);
return cmd;
}
/// <summary>
/// 提交sql语句执行(增删改)
/// </summary>
/// <param name="sql"></param>
/// <param name="spms"></param>
/// <returns>影响行数</returns>
public static int ExecuteNonQuery(string sql, params SqlParameter[] spms)
{
int result = 0;
SqlCommand cmd = PrepareCommand(sql, spms);
try
{
cmd.Connection.Open();
result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
throw new Exception(ex.Message);
}
finally
{
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
}
return result;
}
/// <summary>
/// 提交sql语句返回首行首列的值
/// </summary>
/// <param name="sql"></param>
/// <param name="spms"></param>
/// <returns></returns>
public static object ExecuteScalar(string sql, params SqlParameter[] spms)
{
object result = null;
SqlCommand cmd = PrepareCommand(sql, spms);
try
{
cmd.Connection.Open();
result = cmd.ExecuteScalar();
}
catch (Exception ex)
{
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
throw new Exception(ex.Message);
}
finally
{
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
}
return result;
}
/// <summary>
/// 提交sql语句执行(增删改),bayistuta新增,2011/03/21 17:13
/// </summary>
/// <param name="sql"></param>
/// <param name="spms"></param>
/// <returns>影响行数</returns>
public static int ExecuteNonQuery(string sql, CommandType type, params SqlParameter[] spms)
{
int result = 0;
SqlCommand cmd = PrepareCommand(sql, spms);
cmd.CommandType = type;
try
{
cmd.Connection.Open();
result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
throw new Exception(ex.Message);
}
finally
{
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
}
return result;
}
/// <summary>
/// 提交sql语句返回读取器,bayistuta新增,2011/03/25 21:26
/// </summary>
/// <param name="sql"></param>
/// <param name="spms"></param>
/// <returns></returns>
public static SqlDataReader ExecuteReader(string sql, CommandType type, params SqlParameter[] spms)
{
SqlDataReader reader = null;
SqlCommand cmd = PrepareCommand(sql, spms);
cmd.CommandType = type;
try
{
cmd.Connection.Open();
//关闭reader对象,其对应的连接对象自动关闭
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
if (reader != null)
reader.Close();
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
throw new Exception(ex.Message);
}
return reader;
}
/// <summary>
/// 提交sql语句返回读取器
/// </summary>
/// <param name="sql"></param>
/// <param name="spms"></param>
/// <returns></returns>
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] spms)
{
SqlDataReader reader = null;
SqlCommand cmd = PrepareCommand(sql, spms);
try
{
cmd.Connection.Open();
//关闭reader对象,其对应的连接对象自动关闭
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
if (reader != null)
reader.Close();
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
throw new Exception(ex.Message);
}
return reader;
}
/// <summary>
/// 查询实体类对象集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="spms"></param>
/// <returns></returns>
public static List<T> GetList<T>(string sql, params SqlParameter[] spms)
{
List<T> list = new List<T>();
SqlDataReader reader = ExecuteReader(sql, spms);
while (reader.Read())
{
T t = CreateInstance<T>(reader);
list.Add(t);
}
reader.Close();
return list;
}
/// <summary>
/// 查询单个实体类对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="spms"></param>
/// <returns></returns>
public static T GetSingle<T>(string sql, params SqlParameter[] spms)
{
T t = default(T);
SqlDataReader reader = ExecuteReader(sql, spms);
if (reader.Read())
{
t = CreateInstance<T>(reader);
}
reader.Close();
return t;
} /// <summary>
/// 返回DataTable
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="spms">参数</param>
/// <returns></returns>
public static DataTable GetDataTable(string sql, params SqlParameter[] spms)
{
SqlCommand cmd = PrepareCommand(sql, spms); SqlDataAdapter da = new SqlDataAdapter(cmd); //创建DataAdapter数据适配器实例
DataSet ds = new DataSet();//创建DataSet实例
da.Fill(ds, "tables");//使用DataAdapter的Fill方法(填充),调用SELECT命令
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
return ds.Tables[0];
}
/// <summary>
/// 返回DataTable
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="spms">参数</param>
/// <returns></returns>
public static DataTable GetDataTable(string sql, CommandType cmdType, params SqlParameter[] spms)
{
SqlCommand cmd = PrepareCommand(sql, spms);
cmd.CommandType = cmdType;
SqlDataAdapter da = new SqlDataAdapter(cmd); //创建DataAdapter数据适配器实例
DataSet ds = new DataSet();//创建DataSet实例
da.Fill(ds, "tables");//使用DataAdapter的Fill方法(填充),调用SELECT命令
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
return ds.Tables[0];
}
/// <summary>
/// 查询记录条数
/// </summary>
/// <param name="sql"></param>
/// <param name="spms"></param>
/// <returns></returns>
public static int GetCount(string sql, params SqlParameter[] spms)
{
return (int)ExecuteScalar(sql, spms);
}
/// <summary>
/// 使用反射根据实体类的构造函数创建实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="reader"></param>
/// <returns></returns>
private static T CreateInstance<T>(IDataReader reader)
{
Type type = typeof(T);
T t = (T)Activator.CreateInstance(type, reader);
return t;
} /// <summary>
/// 防sql注入,替换字符串
/// </summary>
/// <param name="val">需要替换的值</param>
/// <returns>替换后的值</returns>
public static string GetParameterValue(string val)
{
return val.Replace("'", "''").Replace("-", "[-]");
}
} }

  

one pragmatical sqlhelper的更多相关文章

  1. 不该活着的SqlHelper和DBHelper

    前言: 还记得刚学ADO.NET的情景么? 还记得当年是怎么从ADO.NET被忽悠到用SqlHelper的么? 话说从入门到走上工作岗位那些年,我们就一直被纯纯地教导或引导,ADO.NET太原始,得封 ...

  2. SqlHelper中IN集合场景下的参数处理

    我手头有个古老的项目,持久层用的是古老的ADO.net.前两天去昆明旅游,其中的一个景点是云南民族村,通过导游介绍知道了一个古老的民族——基诺族,“基”在这个族内代表舅舅,“基诺”意为“跟在舅舅后边” ...

  3. 支持多返回值存储过程的SqlHelper

    public readonly string connStr = ConfigurationManager.ConnectionStrings["sql"].ConnectionS ...

  4. 微软版的SqlHelper.cs类

    一,微软SQLHelper.cs类 中文版: using System; using System.Data; using System.Xml; using System.Data.SqlClien ...

  5. 万能的SqlHelper,麻麻再也不用担心用什么数据库了

    以前只用一种数据库,倒也无所谓,但是再数据库切换的时候,发现代码差不多呀. 最初,两种数据库,大不了写两个SqlHelper,但是多了也就发现代码重用率太低了吧. 因此,下面的SqlHelper诞生了 ...

  6. sqlHelper做增删改查,SQL注入处理,存储值,cookie,session

    一.存储值 eg:登录一个页面,在进入这个页面之前你怎么知道它登没登录呢?[在登录成功之后我们把状态保存起来] 存储值得方式有两种,一种是cookie,一种是session 1.1区别: 代码: if ...

  7. sqlHelper做增删改查

    1.把数据库里面的数据显示出来 sqlHelper怎么用:[网上可以下载,需要可以找楼主要] 1.拷贝到项目,修改它的命名空间等于当前项目名称 2.数据库的连接信息,用户名,密码,登录方式等 < ...

  8. SqlHelper类

    using System; using System.Collections; using System.Collections.Generic; using System.Data; using S ...

  9. .net C# SqlHelper for Oracle

    适用于Oracle的sqlhelper 需要使用ODP.Net,引用Oracle.DataAccess.dll 推荐安装ODAC 代码如下: using System; using System.Co ...

随机推荐

  1. mysql 存储过程 例子

    DROP PROCEDURE IF EXISTS variable_demo; delimiter // CREATE PROCEDURE variable_demo() BEGIN select ' ...

  2. Java代码随机生成图片验证码

    package com.rchm.util.images; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2 ...

  3. python3:判断手机的亮屏状态

    在用python对手机做一些自动化操作时,常常会判断手机的亮屏状态,知晓手机的亮屏状态后才好做进一步的动作,如给屏幕解锁等.  用于了解手机的亮屏情况,有一个adb命令可用: adb shell du ...

  4. Sonya and Robots CodeForces - 1004C (思维题)

    Sonya and Robots time limit per test 1 second memory limit per test 256 megabytes input: standard in ...

  5. HDU:2594-Simpsons’ Hidden Talents

    Simpsons' Hidden Talents Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Ot ...

  6. [USACO]奶牛博览会(DP)

    Description 奶牛想证明他们是聪明而风趣的.为此,贝西筹备了一个奶牛博览会,她已经对N头奶牛进行了面试,确定了每头奶牛的智商和情商. 贝西有权选择让哪些奶牛参加展览.由于负的智商或情商会造成 ...

  7. codeforce830A. Office Keys

    A. Office Keys time limit per test: 2 seconds memory limit per test: 256 megabytes input standard: i ...

  8. C#编程:正则表达式验证身份证校验码-10

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  9. IOS开发---菜鸟学习之路--(二十一)-利用正则表达式解析URL获取其中的参数

    因为项目需要解析URL当中参数的部分,在网上搜索了一下都没有相关的资料. 然后就自己写了一个 其实我就是通过正则表达式来处理URL 进行解析的 好了直接上代码吧 也是非常的简单,大家拷贝过去就可以使用 ...

  10. day05_07 标志位讲解

    continue: 需求:大于5才打印 for i in range(10): if i<6 : continue print(i) continue作用:结束本次循环,继续下次循环 break ...