using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UpdateUserId_ConsoleApp
{
class sqlHelper
{
public static string GetSqlConnectionString()
{
return ConfigurationManager.ConnectionStrings["sqlConnection"].ToString();
}
//适合增删改操作,返回影响条数
public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(GetSqlConnectionString()))
{
using (SqlCommand comm = conn.CreateCommand())
{
try
{
conn.Open();
comm.CommandText = sql;
comm.Parameters.AddRange(parameters);
return comm.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (conn != null && conn.State != ConnectionState.Closed)
conn.Close();
}
}
}
}
//查询操作,返回查询结果中的第一行第一列的值
public static object ExecuteScalar(string sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(GetSqlConnectionString()))
{
using (SqlCommand comm = conn.CreateCommand())
{
try
{
conn.Open();
comm.CommandText = sql;
comm.Parameters.AddRange(parameters);
return comm.ExecuteScalar();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (conn != null && conn.State != ConnectionState.Closed)
conn.Close();
}
}
}
}
//Adapter调整,查询操作,返回DataTable
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters)
{
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, GetSqlConnectionString()))
{
DataTable dt = new DataTable();
adapter.SelectCommand.Parameters.AddRange(parameters);
adapter.Fill(dt);
return dt;
}
}
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);
}
}
}
相关文章
- 12-31python 内置函数enumerate()
- 12-31总结的常用函数(持续更新)
- 12-31sort函数讲解+CF.1684B一道数学理解题目
- 12-31python中的lambda函数用法
- 12-31[Fundamental of Power Electronics]-PART II-8. 变换器传递函数-8.4 变换器传递函数的图形化构建
- 12-31801. 二进制中1的个数(lowbit(n)函数)
- 12-31BZOJ3028食物——生成函数+泰勒展开
- 12-31generator 高阶函数
- 12-31生成函数学习笔记(三)——概率生成函数初探
- 12-31【考研数学】高等数学知识点整理——第一章 函数、极限、连续