Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

[Tips] How to connect database SQL Server Using C#

Tuesday 13 October 2015
|
Read: Completed in minutes

[Tips] How to connect database SQL Server Using C#

First step: You must Import SqlClient into your projects






using System.Data.SqlClient;


My demo will read ini file with key and value same


[DataBase]
ServerName=VILH-PC\SQLEXPRESS
DBName=ManageCustomers
Login=sa
Key=123



"Connect MySQL Server with C#" - Webzone tech tips zidane


This demo using some lib function

WriteLog




public static void WriteLog(string strLogFileName, System.Exception ex)
{
    try
    {                            

         string strDate = "[" +
           DateTime.Today.Year + "-" + DateTime.Today.Month + 
                          "-" + DateTime.Today.Day + " " +
           DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" 
                          + DateTime.Now.Second +
                          "]: ";

         string strLogMessage = " * " + strDate + "Message = " 
              + ex.Message.ToString() + "; TargetSite = " + ex.TargetSite + 
               "; StackTrace = " + ex.StackTrace;

         WriteFile(strLogFileName, strLogMessage, 2, Encoding.UTF8);
     }
     catch { }
}



WriteFile




/// <summary>
/// Ghi Noi Dung strContent vao duong dan strPath
/// \nMode=1: CreateNew (co se ghi de, chua co tao moi) / 2:Append
/// </summary>
/// <param name="strPath" /> Duong Dan file
/// <param name="strContent" /> Noi Dung file
/// <param name="Mode" /> 1: CreateNew (co se ghi de, chua co tao moi) / 2:Append
/// <returns> true -> succeed </returns>
static public bool WriteFile(string szPath, string szContent, int iMode, Encoding en) {
    bool bFlag = false;
    FileStream fs = null;

    try
    {
         switch (iMode)
         {
             case 1:
                 fs = new FileStream(szPath, FileMode.Create);
                 break;

             case 2:
                 fs = new FileStream(szPath, FileMode.Append);
                 break;

             default:
                 fs = new FileStream(szPath, FileMode.Append);
                 break;
         }

         using (StreamWriter sw = new StreamWriter(fs, en))
         {
            sw.WriteLine(szContent);
            sw.Close();
         }
         fs.Close();

         bFlag = true;
    }
    catch
    {
        return bFlag;
    }
    return bFlag;
}






Read Ini File

you can view here


Full source code


/* ---------------------------------------------------
 * Author: ViLH / Zidane (huuvi168@gmail.com) 
 * Email: huuvi168@gmail.com
 * Last Modified: 03-01-2015
 * ---------------------------------------------------
*/

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

namespace ManageCustomers
{
    public class clsConnectDB
    {       
        public static string _connectionString;  

        //protected OleDbConnection _connection = null;
        private SqlConnection _connection = null;

        //protected OleDbDataAdapter _adapter;
        private SqlDataAdapter _adapter;

        //protected OleDbCommand _command;
        private SqlCommand _command;

        public clsConnectDB()
        {
            var iniFile = new clsIniFile(frmMain.APP_CONFIG);

            // server Name: VILH-PC\SQLEXPRESS
            var szServerName = iniFile.Read("ServerName", "DataBase"); 

            // DataBase Name: ManageCustomers            
            var szDBName = iniFile.Read("DBName", "DataBase"); 

            // user name: sa
            var szLogin = iniFile.Read("Login", "DataBase");    

            // password: 123
            var szPassWord = iniFile.Read("Key", "DataBase");   

            _connectionString = "Data Source=" + szServerName + 
               ";Initial Catalog=" + szDBName + " ;User Id=" + 
                szLogin + ";Password=" + szPassWord;

            connect();
        }
              
        public SqlCommand Command
        {
          get { return _command; }
          set { _command = value; }
        }

        public SqlDataAdapter Adapter
        {
          get { return _adapter; }
          set { _adapter = value; }
        }
                      
        public SqlConnection Connection
        {
          get { return _connection; }
          set { _connection = value; }
        }
    
        public static string ConnectionString
        {
            get
            {
                return _connectionString;
            }
            set
            {
                _connectionString = value;
            }
        }

        public void connect()
        {            
            try
            {               
                _connection = new SqlConnection(_connectionString);
                _connection.Open();
            }
            catch (System.Exception ex)
            {
                clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
                throw new Exception(ex.Message);
            }            
        }

        public void disconnect()
        {
            if (_connection != null)
                _connection.Close();
        }

        public ArrayList executeQuery()
        {
            ArrayList arr = null;
            try
            {
                connect();
                _command.Connection = _connection;                
                _adapter = new SqlDataAdapter(_command);
                DataSet dataset = new DataSet();
                _adapter.Fill(dataset);
                arr = ConvertDataSetToArrayList(dataset);
            }
            catch (Exception ex)
            {
                clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
                throw new Exception(ex.Message);
            }
            finally
            {
                disconnect();
            }
            return arr;
        }


        public int executeNonQuery()
        {
            int affectedRow = -1;
            try
            {
                connect();
                _command.Connection = _connection;
                affectedRow = _command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
                throw new Exception(ex.Message);
            }
            finally
            {
                disconnect();
            }
            return affectedRow;
        }

        protected ArrayList ConvertDataSetToArrayList(DataSet dataset)
        {
            ArrayList arr = new ArrayList();
            DataTable dt = dataset.Tables[0];
            int i, n = dt.Rows.Count;
            for (i = 0; i < n; i++)
            {
                object obj = GetDataFromDataRow(dt, i);
                arr.Add(obj);
            }
            return arr;
        }

        protected virtual object GetDataFromDataRow(DataTable dt, int i)
        {
            return null;
        }
                
        public IDataReader executeQuery(string sqlString)
        {            
            _command = new SqlCommand(sqlString, _connection);
            return _command.ExecuteReader();
        }
                
        // update, delete
        public void executeNonQuery(string sqlString)
        {
            try
            {                
                _command = new SqlCommand(sqlString, _connection);
                _command.ExecuteNonQuery();
            }
            catch (System.Exception ex)
            {
                clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
                throw new Exception(ex.Message.ToString());
            }
            finally
            {
                disconnect();
            }

        }
                
        public object executeScalar(string sqlString)
        {
            try {                 
                _command = new SqlCommand(sqlString, _connection);
                return _command.ExecuteScalar();
            }
            catch (System.Exception ex)
            {
                clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
                throw new Exception(ex.Message.ToString());
            }
            finally
            {
                disconnect();
            }            
        }

        /// <summary>
        /// Execute Query to Dataset with sqlstring
        /// </summary>
        public DataSet ExecuteQueryToDataSet(string dbString)
        {
            DataSet ds = new DataSet();

            try
            {
                connect();
                SqlDataAdapter adapter = new SqlDataAdapter(dbString, _connection);
                adapter.Fill(ds);               
            }
            catch (System.Exception ex)
            {
                clsCommon.WriteLog(clsCommon.getLogDailyFileName(), ex);
                throw new Exception(ex.Message.ToString());
            }
            finally
            {
                disconnect();
            }

            return ds;
        }

        public DataTable ExecuteQueryToDataTable(string dbString)
        {
            return ExecuteQueryToDataSet(dbString).Tables[0];
        }
    }
}


If you have any feedback in Connect SQL Server using C#. Please leave your comment, we can discuss about it!

Are you interested in topic How to connect database SQL Server Using C# from Webzone Tech Tips? If you have any thoughts or questions, please share them in the comment section below. I would love to hear from you and chat about it

Webzone tech tips Zidane


🙇🏼 We Appreciate Your Comments and Suggestions - Webzone - all things Tech Tips web development 🙇🏼
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com