• SQLHelper简单版(基础版)


    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace H.DAL
    {
        /// <summary>
        /// 数据库操作帮助类
        /// 此段基础代码为SQLServer数据库帮助类
        ///     如需操作MySQL
        ///     1.将代码中Sql改为MySql
        ///     2.添加MySql.Data.dll引用(可通过官网或NuGet)
        ///     3.using System.Data.SqlClient;替换为using MySql.Data.MySqlClient;
        /// </summary>
        public class SQLHelper
        {
            /// <summary>
            /// 数据库连接字符串
            /// </summary>
            private static string connectionStr = 
           System.Configuration.ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString; public SQLHelper() { } public SQLHelper(string connectionStr) { SQLHelper.connectionStr = connectionStr; } /// <summary> /// 得到连接对象 /// </summary> /// <returns></returns> public static SqlConnection GetConn() { SqlConnection sqlconn = null; sqlconn = new SqlConnection(connectionStr); return sqlconn; } /// <summary> /// 查询操作 /// </summary> /// <param name="sql"></param> /// <returns></returns> public static DataTable GetDataTable(string sql, params SqlParameter[] sp) { using (SqlConnection conn = GetConn()) { conn.Open(); using (SqlDataAdapter sda = new SqlDataAdapter(sql, conn)) { sda.SelectCommand.Parameters.AddRange(sp); DataTable dt = new DataTable(); sda.Fill(dt); return dt; } } } /// <summary> /// 增删改操作 /// </summary> /// <param name="sql">sql语句</param> /// <returns>执行后的条数</returns> public static int ExecuteNonQuery(string sql, params SqlParameter[] sp) { using (SqlConnection conn = GetConn()) { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddRange(sp); int i = cmd.ExecuteNonQuery(); return i; } } } /// <summary> /// 执行一条SQL语句,返回首行首列 /// </summary> /// <param name="sql">sql语句</param> /// <returns>首行首列</returns> public static object ExecuteScalar(string sql, params SqlParameter[] sp) { using (SqlConnection conn = GetConn()) { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddRange(sp); return cmd.ExecuteScalar(); } } } } }

    1.读取微软配置文件使用的System.Configuration.ConfigurationManager,需要添加引用

    2.配置文件中需增加数据库连接节点,类似如下

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <connectionStrings>
        <add name="dbConnection" connectionString="server=.;database=数据库名称;uid=用户名;pwd=密码;"/>
      </connectionStrings>
    </configuration>
  • 相关阅读:
    非凸优化的方法
    随机梯度下降与批量梯度下降
    python requests用于测试
    Vscode中运行js文件或部分代码 ,在下面cmd输出中显示结果
    ts问题处理(2): 'Promise' only refers to a type, but is being used as a value here.
    typeScript入门基础 (1)
    node启动服务报错Node.js Error: Cannot find module express
    能改变this各种情况下的总结,还有没有总结到的,请留言!!
    flutter安装与配置 v1.2.1版本
    vue项目webpack打包后有的文件big 问题
  • 原文地址:https://www.cnblogs.com/ChenRihe/p/5968644.html
Copyright © 2020-2023  润新知