SqlServer数据库连接帮助类
帮助类
/// <summary>
/// 配置获取
/// </summary>
public class DBConfig
{
public static string getBasicConn()
{
return ConfigurationManager.ConnectionStrings["SqlServerDataSource"].ConnectionString;
}
public static string getLteConn()
{
return ConfigurationManager.ConnectionStrings["lte"].ConnectionString;
}
}
/// <summary>
/// 数据库帮助类
/// </summary>
public class SqlDBHelper
{
/// <summary>
/// 链接字符串
/// </summary>
private string connectionString;
public SqlDBHelper()
{
this.connectionString = DBConfig.getBasicConn();
}
public SqlDBHelper(string connectionString)
{
this.connectionString = connectionString;
}
/// <summary>
/// 执行SQL语句
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int ExecuteSqlWithRet(string sql)
{
try
{
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = sql;
connection.Open();
int result = Convert.ToInt32(command.ExecuteScalar());//执行查询,并返回查询所返回的结果集中第一行的第一列。 忽略其他列或行
connection.Close();
return result;
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 执行SQL语句
/// </summary>
/// <param name="sql"></param>
/// <param name="pars"></param>
/// <returns></returns>
public int ExecuteSqlWithRet(string sql, params SqlParameter[] pars)
{
try
{
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = sql;
command.Parameters.AddRange(pars);
connection.Open();
int result = Convert.ToInt32(command.ExecuteScalar());
connection.Close();
return result;
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 执行SQL语句
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int ExecuteSql(string sql)
{
try
{
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = sql;
connection.Open();
int result = command.ExecuteNonQuery();
connection.Close();
return result;
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 执行SQL语句
/// </summary>
/// <param name="sql"></param>
/// <param name="pars"></param>
/// <returns></returns>
public int ExecuteSql(string sql, params SqlParameter[] pars)
{
try
{
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = sql;
command.Parameters.AddRange(pars);
connection.Open();
int result = command.ExecuteNonQuery();
connection.Close();
return result;
}
}
catch (Exception ex)
{
throw;
}
}
/// <summary>
/// 查询数据
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public DataTable GetDataTable(string sql)
{
try
{
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(sql, connection);
sda.Fill(ds);
if (ds != null && ds.Tables.Count > 0)
{
return ds.Tables[0];
}
else
{
return null;
}
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 查询数据
/// </summary>
/// <param name="sql"></param>
/// <param name="pars"></param>
/// <returns></returns>
public DataTable GetDataTable(string sql, params SqlParameter[] pars)
{
try
{
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
DataSet ds = new DataSet();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = sql;
command.Parameters.AddRange(pars);
SqlDataAdapter sda = new SqlDataAdapter(command);
sda.Fill(ds);
if (ds != null && ds.Tables.Count > 0)
{
return ds.Tables[0];
}
else
{
return null;
}
}
}
catch (Exception)
{
throw;
}
}
public DataSet GetDataTableByPage(int start, int pageSize, string table, string columns, string order, string filter)
{
try
{
string sql = "SELECT TOP " + pageSize + " " + columns + " FROM (SELECT ROW_NUMBER() OVER (ORDER BY " + order + " ) AS RowNumber," + columns + " FROM " + table + " {0}) A WHERE RowNumber> " + start + " order by RowNumber ";
sql = string.Format(sql, (filter.Trim() == "" ? "" : (" WHERE " + filter.Trim())));
//记录总数(非结果集记录总数)
string sql_count = "SELECT COUNT(*) FROM " + table;
sql_count += (filter.Trim() == "" ? "" : (" WHERE " + filter));
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
DataSet ds = new DataSet();
ds.Tables.Add("result");
ds.Tables.Add("count");
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand();
sda.SelectCommand.Connection = connection;
sda.SelectCommand.CommandText = sql;
sda.Fill(ds.Tables["result"]);
sda.SelectCommand.CommandText = sql_count;
sda.Fill(ds.Tables["count"]);
return ds;
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 分页查询数据
/// </summary>
public DataSet GetDataTableByPage(int start, int pageSize, string table, string columns, string order, string filter, params SqlParameter[] pars)
{
try
{
string sql = "SELECT TOP " + pageSize + " " + columns + " FROM (SELECT ROW_NUMBER() OVER (ORDER BY " + order + " ) AS RowNumber," + columns + " FROM " + table + " {0}) A WHERE RowNumber> " + start + " ORDER BY " + order;
sql = string.Format(sql, (filter.Trim() == "" ? "" : (" WHERE " + filter.Trim())));
//记录总数(非结果集记录总数)
string sql_count = "SELECT COUNT(*) FROM " + table;
sql_count += (filter.Trim() == "" ? "" : (" WHERE " + filter));
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
DataSet ds = new DataSet();
ds.Tables.Add("result");
ds.Tables.Add("count");
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand();
sda.SelectCommand.Connection = connection;
sda.SelectCommand.Parameters.AddRange(pars);
sda.SelectCommand.CommandText = sql;
sda.Fill(ds.Tables["result"]);
sda.SelectCommand.CommandText = sql_count;
sda.Fill(ds.Tables["count"]);
return ds;
}
}
catch (Exception)
{
throw;
}
}
}
使用
DBHelper helper = new DBHelper();
- 查询
r= helper.ExecuteSqlWithRet(" SELECT * [dbo].[student] where ....... ",
new SqlParameter("@a",""),
new SqlParameter("@b", CreatedTime.ToDateTime()),
new SqlParameter("@c", CreatedTime.ToDateTime())
);
- 更新
helper.ExecuteSql("DELETE FROM [dbo].[student] where ....... ", new SqlParameter("@a", a),
new SqlParameter("@a", b),new SqlParameter("@c", c));
连接
<connectionStrings>
<add name="SqlServerDataSource" connectionString="Server=127.0.0.1;Initial Catalog=StudentDB;User ID=sa;Password=123456" providerName="System.Data.SqlClient"/>
</connectionStrings>
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16592680.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2021-08-16 自定义模型转JSON 之Newtonsoft.Json.dll 、System.Runtime.Serialization.dll和System.Web.Extensions.dll
2021-08-16 JSONStrToList、StrTosJSON
2021-08-16 C#实现连接数据库
2021-08-16 C#前端画表