SqlHelper
Posted gzu_zb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SqlHelper相关的知识,希望对你有一定的参考价值。
首先需要先配置连接字符串:
<connectionStrings> <add name="Sql" connectionString="server=数据库地址;uid=用户名;pwd=密码;database=数据库名" providerName="System.Data.SqlClient"/> </connectionStrings>
SqlHepler类代码如下:
public static class SqlHelper { /// <summary> /// 获取连接字符串 /// </summary> /// <returns>连接字符串</returns> public static string GetSqlConnectionString() { return ConfigurationManager.ConnectionStrings["Sql"].ConnectionString; } /// <summary> /// 封装一个执行的sql 返回受影响的行数 /// </summary> /// <param name="sqlText">执行的sql脚本</param> /// <param name="parameters">参数集合</param> /// <returns>受影响的行数</returns> public static int ExecuteNonQuery(string sqlText, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(GetSqlConnectionString())) { using (SqlCommand cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = sqlText; cmd.Parameters.AddRange(parameters); return cmd.ExecuteNonQuery(); } } } /// <summary> /// 执行sql,返回查询结果中的第一行第一列的值 /// </summary> /// <param name="sqlText">执行的sql脚本</param> /// <param name="parameters">参数集合</param> /// <returns>查询结果中的第一行第一列的值</returns> public static object ExecuteScalar(string sqlText, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(GetSqlConnectionString())) { using (SqlCommand cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = sqlText; cmd.Parameters.AddRange(parameters); return cmd.ExecuteScalar(); } } } /// <summary> /// 执行sql 返回一个DataTable /// </summary> /// <param name="sqlText">执行的sql脚本</param> /// <param name="parameters">参数集合</param> /// <returns>返回一个DataTable</returns> public static DataTable ExecuteDataTable(string sqlText, params SqlParameter[] parameters) { using (SqlDataAdapter adapter = new SqlDataAdapter(sqlText, GetSqlConnectionString())) { DataTable dt = new DataTable(); adapter.SelectCommand.Parameters.AddRange(parameters); adapter.Fill(dt); return dt; } } /// <summary> /// 执行sql脚本 /// </summary> /// <param name="sqlText">执行的sql脚本</param> /// <param name="parameters">参数集合</param> /// <returns>返回一个SqlDataReader</returns> public static SqlDataReader ExecuteReader(string sqlText, params SqlParameter[] parameters) { //SqlDataReader要求,它读取数据的时候有,它独占它的SqlConnection对象,而且SqlConnection必须是Open状态 SqlConnection conn = new SqlConnection(GetSqlConnectionString());//不要释放连接,因为后面还需要连接打开状态 SqlCommand cmd = conn.CreateCommand(); conn.Open(); cmd.CommandText = sqlText; cmd.Parameters.AddRange(parameters); //CommandBehavior.CloseConnection当SqlDataReader释放的时候,顺便把SqlConnection对象也释放掉 return cmd.ExecuteReader(CommandBehavior.CloseConnection); } }
以上是关于SqlHelper的主要内容,如果未能解决你的问题,请参考以下文章
2016-11-2坚持学习Day17微软 推出的SQLHelper