搜索
首页数据库mysql教程C#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);
            }
        }
    }
}



声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何识别和优化MySQL中的慢速查询? (慢查询日志,performance_schema)如何识别和优化MySQL中的慢速查询? (慢查询日志,performance_schema)Apr 10, 2025 am 09:36 AM

要优化MySQL慢查询,需使用slowquerylog和performance_schema:1.启用slowquerylog并设置阈值,记录慢查询;2.利用performance_schema分析查询执行细节,找出性能瓶颈并优化。

MySQL和SQL:开发人员的基本技能MySQL和SQL:开发人员的基本技能Apr 10, 2025 am 09:30 AM

MySQL和SQL是开发者必备技能。1.MySQL是开源的关系型数据库管理系统,SQL是用于管理和操作数据库的标准语言。2.MySQL通过高效的数据存储和检索功能支持多种存储引擎,SQL通过简单语句完成复杂数据操作。3.使用示例包括基本查询和高级查询,如按条件过滤和排序。4.常见错误包括语法错误和性能问题,可通过检查SQL语句和使用EXPLAIN命令优化。5.性能优化技巧包括使用索引、避免全表扫描、优化JOIN操作和提升代码可读性。

描述MySQL异步主奴隶复制过程。描述MySQL异步主奴隶复制过程。Apr 10, 2025 am 09:30 AM

MySQL异步主从复制通过binlog实现数据同步,提升读性能和高可用性。1)主服务器记录变更到binlog;2)从服务器通过I/O线程读取binlog;3)从服务器的SQL线程应用binlog同步数据。

mysql:简单的概念,用于轻松学习mysql:简单的概念,用于轻松学习Apr 10, 2025 am 09:29 AM

MySQL是一个开源的关系型数据库管理系统。1)创建数据库和表:使用CREATEDATABASE和CREATETABLE命令。2)基本操作:INSERT、UPDATE、DELETE和SELECT。3)高级操作:JOIN、子查询和事务处理。4)调试技巧:检查语法、数据类型和权限。5)优化建议:使用索引、避免SELECT*和使用事务。

MySQL:数据库的用户友好介绍MySQL:数据库的用户友好介绍Apr 10, 2025 am 09:27 AM

MySQL的安装和基本操作包括:1.下载并安装MySQL,设置根用户密码;2.使用SQL命令创建数据库和表,如CREATEDATABASE和CREATETABLE;3.执行CRUD操作,使用INSERT,SELECT,UPDATE,DELETE命令;4.创建索引和存储过程以优化性能和实现复杂逻辑。通过这些步骤,你可以从零开始构建和管理MySQL数据库。

InnoDB缓冲池如何工作,为什么对性能至关重要?InnoDB缓冲池如何工作,为什么对性能至关重要?Apr 09, 2025 am 12:12 AM

InnoDBBufferPool通过将数据和索引页加载到内存中来提升MySQL数据库的性能。1)数据页加载到BufferPool中,减少磁盘I/O。2)脏页被标记并定期刷新到磁盘。3)LRU算法管理数据页淘汰。4)预读机制提前加载可能需要的数据页。

MySQL:初学者的数据管理易用性MySQL:初学者的数据管理易用性Apr 09, 2025 am 12:07 AM

MySQL适合初学者使用,因为它安装简单、功能强大且易于管理数据。1.安装和配置简单,适用于多种操作系统。2.支持基本操作如创建数据库和表、插入、查询、更新和删除数据。3.提供高级功能如JOIN操作和子查询。4.可以通过索引、查询优化和分表分区来提升性能。5.支持备份、恢复和安全措施,确保数据的安全和一致性。

与MySQL中使用索引相比,全表扫描何时可以更快?与MySQL中使用索引相比,全表扫描何时可以更快?Apr 09, 2025 am 12:05 AM

全表扫描在MySQL中可能比使用索引更快,具体情况包括:1)数据量较小时;2)查询返回大量数据时;3)索引列不具备高选择性时;4)复杂查询时。通过分析查询计划、优化索引、避免过度索引和定期维护表,可以在实际应用中做出最优选择。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。