C#ADO.NET帮助类

Jun 07, 2016 pm 04:02 PM
system using ヘルプ

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 までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Java ドキュメントの解釈: System クラスの currentTimeMillis() メソッドの使用分析 Java ドキュメントの解釈: System クラスの currentTimeMillis() メソッドの使用分析 Nov 03, 2023 am 09:30 AM

Java ドキュメントの解釈: System クラスの currentTimeMillis() メソッドの使用状況分析、特定のコード例が必要 Java プログラミングでは、System クラスはシステムに関連するいくつかのプロパティと操作をカプセル化する非常に重要なクラスです。その中でも、System クラスでよく使われるメソッドである currentTimeMillis メソッドについて、コード例を示しながら詳しく説明します。 1. currentTimeMillisメソッドの概要

Win10 ブルー スクリーン エラー: システム サービス例外 Win10 ブルー スクリーン エラー: システム サービス例外 Dec 29, 2023 pm 04:04 PM

win10 システムは非常に使いやすく、高度なインテリジェントなシステムであり、互換性が高いため、通常の使用では基本的に問題はありませんが、win10 システムを使用し続けると、システムが不安定になることがあります。 Win10 起動時にブルー スクリーン終了コード SystemServiceException が発生する問題 今日は、Win10 起動時にブルー スクリーン終了コード SystemServiceException が発生する問題の解決策を紹介します。必要な場合は、すぐにダウンロードしてください。 win10systemserviceException ブルー スクリーンの解決策: 方法 1: 1. Windows キー + R を使用してファイル名を指定して実行を開き、「contr」と入力します。

コンピュータシステムとは何ですか? コンピュータシステムとは何ですか? Feb 22, 2023 am 10:25 AM

コンピュータ システムは比較的一般的なシステム プロセスです。プロセスを表示すると、システムが表示されることがよくあります。このプロセスは単にコンピュータ システムを意味します。ただし、system.exe プロセスがコンピュータ上に表示された場合は、適時に削除する必要があります。これはトロイの木馬ウイルスによって生成されたファイルであり、実際のシステムの背後には exe サフィックスはありません。

Windows7 英語版システムのダウンロード Windows7 英語版システムのダウンロード Jul 15, 2023 pm 07:45 PM

ネットユーザーは Windows 7 システムによく精通していると思いますが、Windows 7 英語版システムについて聞いたことがありますか? 多くのネットユーザーは Windows 7 英語版システムについて聞いたことがあると思いますが、Windows 7 英語版システムを探している友人もいます。ダウンロードするバージョン システム. 今日は、ネチズンが英語で win7 のオリジナル バージョンを理解できるように、編集者が英語での win7 のオリジナル バージョンの紹介を皆さんと共有するつもりです。以下は、英語版の Windows 7 システムをダウンロードする場所を示しています。 win7 のオリジナルの英語システムは、サブスクリプション ダウンロード用に MSDN にリリースされました。正式な英語統合バージョンは、統合 SP1 を含む Windows7 CD イメージである Windows7WithSP1 として最初にリリースされました。複数の言語に対応するスタンドアロン SP1 が含まれています

Microsoft、System Center 2022 の一般提供を発表 Microsoft、System Center 2022 の一般提供を発表 Apr 14, 2023 am 09:40 AM

Microsoft は、System Center 2022 の提供を発表しました。最新バージョンでは、System Center Operations Manager (SCOM)、Virtual Machine Manager (VMM)、System Center Orchestrator (SCORCH)、Service Manager (SM)、および Data Protection Manager が提供されます。

JavaでObjectクラスとSystemクラスを使用するにはどうすればよいですか? JavaでObjectクラスとSystemクラスを使用するにはどうすればよいですか? Apr 23, 2023 pm 11:28 PM

オブジェクトはすべての Java クラスの基本クラスであり、クラス継承構造全体の最上位であり、最も抽象的なクラスです。誰もが毎日、toString()、equals()、hashCode()、wait()、notify()、getClass() などのメソッドを使用していますが、おそらくそれらが Object のメソッドであることを認識しておらず、見向きもしません。 Object には他にどのようなメソッドがあるのか​​、そしてなぜこれらのメソッドを Object に配置する必要があるのか​​を考えてみましょう。 1. JavaObject クラスの概要 - すべてのクラスのスーパー クラス Object は Java クラス ライブラリの特別なクラスであり、すべてのクラスの親クラスでもあります。言い換えれば、Java では、任意のタイプのオブジェクトを Object タイプに割り当てることができます。

今すぐブラウザで MacOS 7 と MacOS 8 を実行する方法 今すぐブラウザで MacOS 7 と MacOS 8 を実行する方法 Apr 18, 2023 am 11:04 AM

1990 年代の Macintosh にタイムスリップし、ブラウザ ウィンドウで System 7 と MacOS 8 の完全な仮想インストールを実行します。 1990 年代の Mac ソフトウェアの新しい仮想バージョンの欠点の 1 つは、2020 年代の Mac の速度で動作することです。あなたは MacSE/30 または Quadra700 を見ていますが、すべてが Apple Silicon と同じくらい高速です。これらのシミュレートされたオペレーティング システムで実際に作業することができ、ドキュメントやファイルを macOS Monterey の内外にドラッグすることもできます。ただし、実用的な目的であっても、純粋に楽しむためであっても、次の方法で行うことができます。

MySQLの使い方 MySQLの使い方 Jun 03, 2023 pm 08:43 PM

例 通常、関連テーブルクエリを実行すると、通常は次のようになります: select*from table 1 innerjoin table 2 on table 1. Same columns = table 2. Same columns; これを次のように変更できます。同じ効果です。テーブル 1 からテーブル 1 の列を選択します。テーブル 1 の内部結合テーブル 2 です。同じ列 = テーブル 2。同じ列です。その後、(同じ列) を使用して select*from テーブル 1 内部結合テーブル 2 に変更することもできます。最初の SELECT*FROMtype、articlewheretype.id=article.type_id;2 番目の SELECT*FROMtypeinnerjoi

See all articles