Home Database Mysql Tutorial 用于SqlServer数据库的SqlServerHelper.cs类,及其调用例子

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

Jun 07, 2016 pm 03:10 PM
sqlserver database

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;
        }

    }
}
Copy after login

Copy after login

调用方法:

 

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

            //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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Where is the navicat database file? Where is the navicat database file? Apr 23, 2024 am 10:57 AM

The location where the Navicat database configuration files are stored varies by operating system: Windows: The user-specific path is %APPDATA%\PremiumSoft\Navicat\macOS: The user-specific path is ~/Library/Application Support/Navicat\Linux: The user-specific path is ~/ .config/navicat\The configuration file name contains the connection type, such as navicat_mysql.ini. These configuration files store database connection information, query history, and SSH settings.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to write navicat database connection url How to write navicat database connection url Apr 24, 2024 am 02:33 AM

The format of the Navicat connection URL is: protocol://username:password@host:port/database name? Parameters, which contain the information required for the connection, including protocol, username, password, hostname, port, database name and optional parameter.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to connect to remote database using Golang? How to connect to remote database using Golang? Jun 01, 2024 pm 08:31 PM

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

See all articles