search
HomeDatabaseMysql TutorialC#ADO.NET帮助类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.SqlClient;namespace DBComm{ static class DBCommand { public class DBParameters { private SqlCommand m_owner = null; publi

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DBComm
{
    static class DBCommand
    {
        public class DBParameters
        {
            private SqlCommand m_owner = null;
            public DBParameters(SqlCommand owner)
            {
                m_owner = owner;
            }
            public SqlParameterCollection P()
            {
                return m_owner.Parameters;
            }
        };

        public static bool BulkToDB(string tabname, DataTable dt, params string[] destColumnNames)
        {
            bool bRet = false;
            do
            {
                    if (dt == null)
                        break;
                    if (dt.Rows.Count == 0)
                        break;
                    using (SqlConnection conn = DBConn.GetConn())
                    {
                        if (conn == null)
                            break;

                        SqlBulkCopy bulkcopy = new SqlBulkCopy(conn);
                        if (bulkcopy == null)
                            break;

                        bulkcopy.DestinationTableName = tabname;
                        bulkcopy.BulkCopyTimeout = 30;
                        if (destColumnNames.Length == 0)
                        {
                            foreach (DataColumn col in dt.Columns)
                                bulkcopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
                        }
                        else
                        {
                            if (destColumnNames.Length == dt.Columns.Count)
                            {
                                for (int i = 0; i < destColumnNames.Length; ++i)
                                {
                                    bulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, destColumnNames[i]);
                                }
                            }
                        }
                        bulkcopy.BatchSize = dt.Rows.Count;
                        try
                        {
                            bulkcopy.WriteToServer(dt);
                        }
                        catch (System.Exception e)
                        {
                            string err = e.Message;
                            break;
                        }
                        finally
                        {
                            bulkcopy.Close();
                        }
                    }
                    bRet = true;
            } while (false);
            return bRet;
        }

        public static DBParameters ExecProcNonQuery(string proc_name, object[] paraValues)
        {
            using (SqlConnection conn = DBConn.GetConn())
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = proc_name;

                AddInParaValues(cmd, paraValues);
                cmd.ExecuteNonQuery();

                return new DBParameters(cmd);
            }
        }

        public delegate T[] FillValues<T>(SqlDataReader reader);

        public static T[] QuerySomes<T>(string sql, FillValues<T> fill)
        {
            using (SqlConnection conn = DBConn.GetConn())
            {
                T[] result = null;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = sql;


                SqlDataReader reader = null;
                lock (reader = cmd.ExecuteReader())
                {
                    try
                    {
                        result = fill(reader);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(e.StackTrace);
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
                return result;
            }
        }

        public delegate object FillValue(SqlDataReader reader);

        public static object QuerySome(string sql, FillValue fill)
        {
            using (SqlConnection conn = DBConn.GetConn())
            {
                object result = null;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = sql;
                SqlDataReader reader = null;
                lock (reader = cmd.ExecuteReader())
                {
                    try
                    {
                        result = fill(reader);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(e.StackTrace);
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
                return result;
            }
        }

        public static object FillResultValue(SqlDataReader reader)
        {
            object o = null;
            if (reader.Read())
            {
                o = reader.GetValue(0);
            }
            return o;
        }

        public static bool QueryBoolean(string sql)
        {
            return Convert.ToBoolean(QuerySome(sql, new FillValue(FillResultValue)));
        }

        public static byte[] QueryBytes(string sql)
        {
            return (byte[])(QuerySome(sql, new FillValue(FillResultValue)));
        }

        public static int QueryInteger(string sql)
        {
            return Convert.ToInt32(QuerySome(sql, new FillValue(FillResultValue)));
        }


        public static string QueryStr(string sql)
        {
            return QuerySome(sql, new FillValue(FillResultValue)) as string;
        }

        private static string[] FillStrsValue(SqlDataReader reader)
        {
            List<string> lststr = new List<string>();
            while (reader.Read())
            {
                lststr.Add(reader.GetString(0));
            }
            return lststr.ToArray();
        }

        public static string[] QueryStrs(string sql)
        {
            return QuerySomes(sql, new FillValues<string>(FillStrsValue));
        }

        private static bool[] FillBooleansValue(SqlDataReader reader)
        {
            List<bool> lstbool = new List<bool>();
            while (reader.Read())
            {
                lstbool.Add(reader.GetBoolean(0));
            }
            return lstbool.ToArray();
        }

        public static bool[] QueryBooleans(string sql)
        {
            return QuerySomes(sql, new FillValues<bool>(FillBooleansValue));
        }

        public static void ExecCmd(string sql)
        {
            using (SqlConnection conn = DBConn.GetConn())
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
            }
        }
        /// <summary>
        /// 获取存储过程的参数列表
        /// </summary>
        /// <param name="proc_Name">存储过程名称</param>
        /// <returns>DataTable</returns>
        private static DataTable GetParameters(SqlConnection conn, string proc_Name)
        {
            SqlCommand comm = new SqlCommand("dbo.sp_sproc_columns", conn);
            comm.CommandType = CommandType.StoredProcedure;
            comm.Parameters.AddWithValue("@procedure_name", (object)proc_Name);
            SqlDataAdapter sda = new SqlDataAdapter(comm);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            return dt;
        }
        /// <summary>
        /// 为 SqlCommand 添加参数及赋值
        /// </summary>
        /// <param name="comm">SqlCommand</param>
        /// <param name="paraValues">参数数组(必须遵循存储过程参数列表的顺序)</param>
        private static void AddInParaValues(SqlCommand comm, params object[] paraValues)
        {
            using (SqlConnection conn = DBConn.GetConn())
            {
                comm.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.Int));
                comm.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;
                if (paraValues != null)
                {
                    DataTable dt = GetParameters(conn, comm.CommandText);
                    int i = 0;
                    foreach (DataRow row in dt.Rows)
                    {
                        string key = row[3].ToString();
                        if (key != "@RETURN_VALUE")
                        {
                            int value = int.Parse(row[4].ToString());
                            if (value == 1)
                            {
                                comm.Parameters.AddWithValue(key, paraValues[i]);
                            }
                            else if (value == 2)//value为2则是输出参数
                            {
                                comm.Parameters.AddWithValue(key, paraValues[i]).Direction = ParameterDirection.Output;
                                //comm.Parameters[key].Direction = ParameterDirection.Output;
                            }
                            comm.Parameters[key].Size = Convert.ToInt32(row[7].ToString());
                            i++;
                        }
                    }
                }
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace DBComm
{
    class DBConn
    {
        private static string m_connstr;

        public static string ConnString
        {
            get { return m_connstr; }
            private set { m_connstr = value; }
        }

        static DBConn() 
        {
            SqlConnectionStringBuilder connStr = new SqlConnectionStringBuilder();
            connStr.DataSource = ".";
            connStr.InitialCatalog = "test";
            connStr.IntegratedSecurity = true;

            connStr.Pooling = true; //开启连接池
            connStr.MinPoolSize = 0; //设置最小连接数为0
            connStr.MaxPoolSize = 100; //设置最大连接数为100             
            connStr.ConnectTimeout = 10; //设置超时时间为10秒

            ConnString = connStr.ConnectionString;
            //ConnectDB(ConnString);
        }

        public static SqlConnection GetConn()
        {
            SqlConnection conn = new SqlConnection(ConnString);
            conn.Open();
            return conn;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace DBComm
{
    static class DBTableSource
    {
        public static DataTable GetSource(SqlConnection conn, string strsql)
        {
            DataTable dt = null;
            SqlCommand cmd = null;
            SqlDataAdapter ad = null;
            try
            {
                lock (dt = new DataTable())
                {
                    if (conn is SqlConnection)
                    {
                        cmd = new SqlCommand(strsql, conn);
                        ad = new SqlDataAdapter((SqlCommand)cmd);
                    }

                    dt.Clear();
                    ad.Fill(dt);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return dt;
        }

        public static DataTable Source(string strsql)
        {
            using (SqlConnection conn = DBConn.GetConn())
            {
                return GetSource(conn, strsql);
            }
        }
    }
}



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java文档解读:System类的currentTimeMillis()方法用法解析Java文档解读:System类的currentTimeMillis()方法用法解析Nov 03, 2023 am 09:30 AM

Java文档解读:System类的currentTimeMillis()方法用法解析,需要具体代码示例在Java编程中,System类是一个非常重要的类,其封装了与系统相关的一些属性和操作。其中,currentTimeMillis方法是System类中非常常用的一个方法,本文将对该方法做详细解读并提供代码示例。一.currentTimeMillis方法概述

Win10蓝屏错误:系统服务异常Win10蓝屏错误:系统服务异常Dec 29, 2023 pm 04:04 PM

win10系统是一款非常好用的高智能系统,强大的兼容性可以确保系统在正常的使用过程中基本不会出现任何的问题,但是随着人们对win10系统的不断使用有时候系统也会出现win10开机蓝屏终止代码systemserviceexception的问题,今天小编就为大家带来了win10开机蓝屏终止代码systemserviceexception的解决办法有需要的话就快来下载吧。win10systemserviceexception蓝屏的解决办法:方法一:1、使用Windows键+R打开运行,输入“contr

电脑的system是什么电脑的system是什么Feb 22, 2023 am 10:25 AM

电脑的system是比较常见的一种系统进程,在查看进程的时候经常会看到system,这个进程简单来说就是电脑系统的意思;但是,如果电脑中出现了system.exe的进程,需要及时删除,这是一个木马病毒生成的文件,真正的system后边是没有exe后缀的。

微软宣布 System Center 2022 全面上市微软宣布 System Center 2022 全面上市Apr 14, 2023 am 09:40 AM

微软已宣布System Center 2022 的可用性。最新版本带来了 System Center Operations Manager (SCOM)、Virtual Machine Manager (VMM)、System Center Orchestrator (SCORCH)、Service Manager (SM) 和 Data Protection Manager

windows7英文版系统下载windows7英文版系统下载Jul 15, 2023 pm 07:45 PM

相信网友们都对windows7系统非常熟悉,那大家听说过windows7英文版系统吗?相信有非常多的网友都对windows7英文版系统略有耳闻,不过有的朋友找windows7英文版系统下载,今天小编就要把win7英文原版系统介绍分享给大家,让网友们都能了解到英文win7原版系统。下面就是告诉你windows7英文版系统哪里下载。win7英文原版系统已发布到MSDN订阅下载,官方首先发布的英文集成版,Windows7WithSP1,即集成SP1的Windows7光盘镜像。包含适用于多语言的SP1独

今天如何在浏览器中运行 MacOS 7 和 MacOS 8今天如何在浏览器中运行 MacOS 7 和 MacOS 8Apr 18, 2023 am 11:04 AM

时光倒流回到1990年代的Macintosh,在浏览器窗口中运行System7和MacOS8的完整虚拟安装。1990年代Mac软件的新虚拟版本存在一个缺陷,那就是它们以2020年代Mac的速度运行。您看到的是MacSE/30或Quadra700,但一切都与AppleSilicon一样快。您可以在这些模拟操作系统中进行实际工作,它们甚至可以将文档或文件从macOSMonterey拖入和拖出。但无论是出于某些实际目的还是更可能是为了纯粹的乐趣,这里是如何

王者荣耀共赴花期帮助好友翻牌的方法王者荣耀共赴花期帮助好友翻牌的方法Mar 24, 2024 pm 12:31 PM

在王者荣耀共赴花期中,我们可以帮助好友翻牌来获取花露,那么怎么帮好友翻牌呢?下面小编就为大家带来了王者荣耀共赴花期帮助好友翻牌的方法。王者荣耀共赴花期怎么帮好友翻牌1、想要帮好友翻牌需要好友邀请翻牌才行。2、让你的好友邀请你翻牌,然后你同意进行翻牌即可。3、好友邀请翻牌的操作方式和帮助好友翻牌的操作方式是一样的。4、只是帮好友翻牌需要你的朋友先操作。好友翻牌操作方式1、首先打开共赴花期活动页面,在页面中点击“获取花露”。2、选择好友成功帮助翻牌一次,点击“去完成”。3、选择需要好友帮忙翻的牌,再

如何使用Java中的Object类和System类?如何使用Java中的Object类和System类?Apr 23, 2023 pm 11:28 PM

Object是java所有类的基类,是整个类继承结构的顶端,也是最抽象的一个类。大家天天都在使用toString()、equals()、hashCode()、waite()、notify()、getClass()等方法,或许都没有意识到是Object的方法,也没有去看Object还有哪些方法以及思考为什么这些方法要放到Object中。一、JavaObject类简介-所有类的超类Object是Java类库中的一个特殊类,也是所有类的父类。也就是说,Java允许把任何类型的对象赋给Object类型的

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment