search
HomeDatabaseMysql Tutorial用于SqlServer数据库的SqlServerHelper.cs类,及其调用例子

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Configuration;using System.Data;using System.Data.SqlClient;namespace demo{ public abstract class SqlServerHelper { public static string ConnStr

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

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace demo
{
    public abstract class SqlServerHelper
    {
        public static string ConnString = string.Empty;

        public static string Conn_Config_Str_Name = string.Empty;

        public static string Conn_Server = string.Empty;
        public static string Conn_DBName = string.Empty;
        public static string Conn_Uid = string.Empty;
        public static string Conn_Pwd = string.Empty;

        private static string _ConnString
        {
            get
            {
                if (!string.IsNullOrEmpty(ConnString))
                    return ConnString;

                object oConn = ConfigurationManager.ConnectionStrings[Conn_Config_Str_Name];
                if (oConn != null && oConn.ToString() != "")
                    return oConn.ToString();

                return string.Format(@"server={0};database={1};uid={2};password={3}", Conn_Server, Conn_DBName, Conn_Uid, Conn_Pwd);
            }
        }

        // 测试连接
        public static bool TestConn()
        {
            SqlConnection myConn = null;
            bool bResult = false;
            try
            {
                myConn = new SqlConnection(_ConnString);
                myConn.Open();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (myConn != null && myConn.State.ToString() == "Open")
                    bResult = true;
            }

            myConn.Close();

            return bResult;
        }

        // 取datatable
        public static DataTable GetDataTable(out string sError, string sSQL)
        {
            DataTable dt = null;
            sError = string.Empty;

            try
            {
                SqlConnection conn = new SqlConnection(_ConnString);
                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                comm.CommandText = sSQL;
                SqlDataAdapter dapter = new SqlDataAdapter(comm);
                dt = new DataTable();
                dapter.Fill(dt);
            }
            catch (Exception ex)
            {
                sError = ex.Message;
            }

            return dt;
        }

        // 取dataset
        public static DataSet GetDataSet(out string sError, string sSQL)
        {
            DataSet ds = null;
            sError = string.Empty;

            try
            {
                SqlConnection conn = new SqlConnection(_ConnString);
                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                comm.CommandText = sSQL;
                SqlDataAdapter dapter = new SqlDataAdapter(comm);
                ds = new DataSet();
                dapter.Fill(ds);
            }
            catch (Exception ex)
            {
                sError = ex.Message;
            }

            return ds;
        }

        // 取某个单一的元素
        public static object GetSingle(out string sError, string sSQL)
        {
            DataTable dt = GetDataTable(out sError, sSQL);
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0][0];
            }

            return null;
        }

        // 取最大的ID
        public static Int32 GetMaxID(out string sError, string sKeyField, string sTableName)
        {
            DataTable dt = GetDataTable(out sError, "select isnull(max([" + sKeyField + "]),0) as MaxID from [" + sTableName + "]");
            if (dt != null && dt.Rows.Count > 0)
            {
                return Convert.ToInt32(dt.Rows[0][0].ToString());
            }

            return 0;
        }

        // 执行 insert,update,delete 动作,也可以使用事务
        public static bool UpdateData(out string sError, string sSQL, bool bUseTransaction = false)
        {
            int iResult = 0;
            sError = string.Empty;

            if (!bUseTransaction)
            {
                try
                {
                    SqlConnection conn = new SqlConnection(_ConnString);
                    if (conn.State != ConnectionState.Open)
                        conn.Open();
                    SqlCommand comm = new SqlCommand();
                    comm.Connection = conn;
                    comm.CommandText = sSQL;
                    iResult = comm.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    sError = ex.Message;
                    iResult = -1;
                }
            }
            else // 使用事务
            {
                SqlTransaction trans = null;
                try
                {
                    SqlConnection conn = new SqlConnection(_ConnString);
                    if (conn.State != ConnectionState.Open)
                        conn.Open();
                    trans = conn.BeginTransaction();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandText = sSQL;
                    cmd.Transaction = trans;
                    iResult = cmd.ExecuteNonQuery();
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    sError = ex.Message;
                    iResult = -1;
                    trans.Rollback();
                }
            }

            return iResult > 0;
        }

    }
}


调用方法:

 

一,先设置数据库连接的信息

            //SqlServerHelper.ConnString = @"server=电脑名 或 电脑IP;database=数据库名;uid=数据库登录名;password=数据库登录密码";

            SqlServerHelper.Conn_Config_Str_Name = @"ConnString";  // ConnString的信息在 App.Config里设置                         //SqlServerHelper.Conn_Server = @"电脑名 或 电脑IP";            //SqlServerHelper.Conn_DBName = "数据库名";            //SqlServerHelper.Conn_Uid = "数据库登录名";            //SqlServerHelper.Conn_Pwd = "数据库登录密码";

 

二, App.Config

 

       

 

三,  读取 datatable / dataset 数据

           private void InitGrid()           {

            string sSQL = "select * from test";

            string sError = string.Empty;

            DataTable dt = SqlServerHelper.GetDataTable(out sError, sSQL);

            //DataSet dt = SqlServerHelper.GetDataSet(out sError, sSQL);

            dataGridView1.DataSource = dt;

            if (!string.IsNullOrEmpty(sError))                Common.DisplayMsg(this.Text, sError);

           }

 

四,插入,修改,删除 数据 (都调用SqlServerHelper.UpdateData方法)

            // 插入

            string  sError = string.Empty;            int iMaxID = SqlServerHelper.GetMaxID(out sError, "id", "test") + 1;            string sSql = "insert into test select " + iMaxID + ",'name" + iMaxID + "','remark" + iMaxID + "'";            sError = string.Empty;            bool bResult = SqlServerHelper.UpdateData(out sError, sSql, true);            if (bResult)                Common.DisplayMsg(this.Text, "插入成功");            else                Common.DisplayMsg(this.Text, sError);

            InitGrid();

 

            // 修改

            sError = string.Empty;            int iMaxID = SqlServerHelper.GetMaxID(out sError, "id", "test");            string sSql = "update test set name='name_jonse',remark='remark_jonse' where id=" + iMaxID;            sError = string.Empty;            bool bResult = SqlServerHelper.UpdateData(out sError, sSql, true);            if (bResult)                Common.DisplayMsg(this.Text, "修改成功");            else                Common.DisplayMsg(this.Text, sError);

            InitGrid();

 

             // 删除

            sError = string.Empty;            int iMaxID = SqlServerHelper.GetMaxID(out sError, "id", "test");            string sSql = "delete from test where id=" + iMaxID;            sError = string.Empty;            bool bResult = SqlServerHelper.UpdateData(out sError, sSql);            if (bResult)                Common.DisplayMsg(this.Text, "删除成功");            else                Common.DisplayMsg(this.Text, sError);

            InitGrid();

 

五,其它

 

       public static void DisplayMsg(string sCaption, string sMsg)       {           sMsg = sMsg.TrimEnd('!').TrimEnd('!') + " !";           MessageBox.Show(sMsg, sCaption);       }

 

 

 

 

         

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
MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

MySQL String Data Types: A Comprehensive GuideMySQL String Data Types: A Comprehensive GuideMay 08, 2025 am 12:14 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,idealforconsistentlengthdatalikecountrycodes;2)VARCHARforvariable-lengthstrings,suitableforfieldslikenames;3)TEXTtypesforlargertext,goodforblogpostsbutcanimpactperformance;4)BINARYandVARB

Mastering MySQL BLOBs: A Step-by-Step TutorialMastering MySQL BLOBs: A Step-by-Step TutorialMay 08, 2025 am 12:01 AM

TomasterMySQLBLOBs,followthesesteps:1)ChoosetheappropriateBLOBtype(TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB)basedondatasize.2)InsertdatausingLOAD_FILEforefficiency.3)Storefilereferencesinsteadoffilestoimproveperformance.4)UseDUMPFILEtoretrieveandsaveBLOBsco

BLOB Data Type in MySQL: A Detailed Overview for DevelopersBLOB Data Type in MySQL: A Detailed Overview for DevelopersMay 07, 2025 pm 05:41 PM

BlobdatatypesinmysqlareusedforvoringLargebinarydatalikeImagesoraudio.1) Useblobtypes (tinyblobtolongblob) Basedondatasizeneeds. 2) Storeblobsin Perplate Petooptimize Performance.3) ConsidersxterNal Storage Forel Blob Romana DatabasesizerIndimprovebackupupe

How to Add Users to MySQL from the Command LineHow to Add Users to MySQL from the Command LineMay 07, 2025 pm 05:01 PM

ToadduserstoMySQLfromthecommandline,loginasroot,thenuseCREATEUSER'username'@'host'IDENTIFIEDBY'password';tocreateanewuser.GrantpermissionswithGRANTALLPRIVILEGESONdatabase.*TO'username'@'host';anduseFLUSHPRIVILEGES;toapplychanges.Alwaysusestrongpasswo

What Are the Different String Data Types in MySQL? A Detailed OverviewWhat Are the Different String Data Types in MySQL? A Detailed OverviewMay 07, 2025 pm 03:33 PM

MySQLofferseightstringdatatypes:CHAR,VARCHAR,BINARY,VARBINARY,BLOB,TEXT,ENUM,andSET.1)CHARisfixed-length,idealforconsistentdatalikecountrycodes.2)VARCHARisvariable-length,efficientforvaryingdatalikenames.3)BINARYandVARBINARYstorebinarydata,similartoC

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.