How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

Rate It (1)

Last post 04-06-2009 2:37 PM by Simon Deshaies. 53 replies.

Sort Posts:

  • How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    12-12-2007, 10:34 PM
    • Member
      144 point Member
    • Simon Deshaies
    • Member since 11-17-2007, 10:59 AM
    • Montréal, Canada
    • Posts 70
    How To: Connect to SQL using C# and SELECT, INSERT or UPDATE ? 

    UPDATED! 
    Since I initially wrote this how to I’ve improved the integration of this class quite a bit, you may read the new how to here, and get the revised sample here.

    ARCHIVED
    We all know how to insert a SQL query using ASP.NET the inconvenient in this is that you let the end user see some of your private code and information on your application architecture.

    Here I demonstrate how to use the C# in a code behind page to INSERT, SELECT or UPDATE an existing SQL database. In this example I will be using the Microsoft SQL Express Server. Also the connection string in this example is for a local server with integrated security; if you need to connect to an external Server or a MySQL Server go to connectionstring.com to get the replacement connection string code.

    First off unlike asp.net insert you don’t use a connection string in the web.config, so no changes need to be done there.

     

    ASPX

    Create an ASPX page with code behind.

    In that page you will add 2 text boxes with a button and double click the button to create the event in the code behind then add a label so we can keep track of the status. Just to make it real easy here’s the ASPX code.

    <form id="form1" runat="server">
    <div>
    <center>
    <asp:TextBox ID="TextBox1" runat="server">
    </
    asp:TextBox><br />
    <asp:TextBox ID="TextBox2" runat="server">
    </
    asp:TextBox><br />
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /><br /><br />
    <asp:Label ID="Label1" runat="server" Text="Page Loaded"></asp:Label><br />
    </center>
    </div>
    </form>


    C# Code Behind

    You may insert this hilly commented code in the C# but understanding it first is the best way to go about it.

    //Add the following namespace

    using System.Data;
    using System.Data.Sql;
    using System.Data.SqlClient;


    public partial class _Default : System.Web.UI.Page
    {
        //Here I like to use a region to warp the SQL Connection.
        #region SQLConnection
        //Here I declare a couple of items i'm gona use and asign the database name.
        public SqlConnection mySqlConnection;
        public String currentDatabase = "myDatabase";
        public SqlCommand mySqlCommand;
        public SqlDataReader mySqlDataReader;

        //This is how i'm gona be closing my connection.
        private void closeConn()
        {
            if (mySqlConnection != null)
            {
                if (mySqlConnection.State == ConnectionState.Open)
                {
                    mySqlConnection.Close();
                }
                mySqlConnection.Dispose();
            }
        }

        //Here is where I create my connection.
        private SqlConnection createConn(string database)
        {
            // Here you define your server. Values can not be NULL.        //Database Server Name.
            string myDSN = "SQLEXPRESS";

            //Local Server Name.
            string myLSN = "MyComputer";

            //Define the type of security, 'TRUE' or 'FALASE'.
            string mySecType = "TRUE";

            //Here you have your connection string you can edit it here.
            string mySqlConnectionString = ("server=" + myLSN + "\\" + myDSN + ";database=" + database + ";Integrated Security=" + mySecType);

            //If you wish to use SQL security, well just make your own connection string...
            // I make sure I have declare what mySqlConnection stand for.
           if (mySqlConnection == null) { mySqlConnection = new SqlConnection(); };

           // Since i will be reusing the connection I will try this it the connection dose not exist.
           if (mySqlConnection.ConnectionString == string.Empty || mySqlConnection.ConnectionString == null)
           {
                // I use a try catch stament cuz I use 2 set of arguments to connect to the database
                try
                {
                    //First I try with a pool of 5-40 and a connection time out of 4 seconds. then I open the connection.
                    mySqlConnection.ConnectionString = "Min Pool Size=5;Max Pool Size=40;Connect Timeout=4;" + mySqlConnectionString + ";";
                    mySqlConnection.Open();
                }
                catch (Exception)
                {
                    //If it did not work i try not using the pool and I give it a 45 seconds timeout.
                    if (mySqlConnection.State != ConnectionState.Closed)
                    {
                        mySqlConnection.Close();
                    }
                    mySqlConnection.ConnectionString = "Pooling=false;Connect Timeout=45;" + mySqlConnectionString + ";";
                    mySqlConnection.Open();
                }
                return mySqlConnection;
            }
            //Here if the connection exsist and is open i try this.
            if (mySqlConnection.State != ConnectionState.Open)
            {
                 try
                {
                    mySqlConnection.ConnectionString = "Min Pool Size=5;Max Pool Size=40;Connect Timeout=4;" + mySqlConnectionString + ";";
                    mySqlConnection.Open();
                }
                catch (Exception)
                {
                    if (mySqlConnection.State != ConnectionState.Closed)
                    {
                        mySqlConnection.Close();
                    }
                    mySqlConnection.ConnectionString = "Pooling=false;Connect Timeout=45;" + mySqlConnectionString + ";";
                    mySqlConnection.Open();
                }
            }
            return mySqlConnection;
        }
        #endregion
        // And there you go you can now connect to the SQL Server

        protected void Button1_Click(object sender, EventArgs e)
        {
            // So all we done erlier is used here In the event we create the connection.
            createConn("myDatabase");
            //We create the command to read the database then we will INSERT or UPDATE.
            mySqlCommand = mySqlConnection.CreateCommand();
            //Here in the command text you put your sql select statment
            mySqlCommand.CommandText = "SELECT textBox1 = @textBox1 FROM dbo.table1 WHERE textBox2 = @textBox2";
            //I like to set the type of data I will be inserting here. Then I set where will the data come from and repeat for each data string.
            mySqlCommand.Parameters.Add("@textBox1", SqlDbType.VarChar);
            mySqlCommand.Parameters["@textBox1"].Value = TextBox1.Text;

            mySqlCommand.Parameters.Add("@textBox2", SqlDbType.VarChar);
            mySqlCommand.Parameters["@textBox2"].Value = TextBox2.Text;
            //I execute the reader.
            mySqlDataReader = mySqlCommand.ExecuteReader();
            // If the database dose not have row i will insert the data otherwise I
            // will just close the connection so I make sure i dont override any thing.
            if (!mySqlDataReader.HasRows)
            {
                mySqlDataReader.Close();
                //If you had to do an UPDATE here insted of an INSERT statment you would use a UPDATE statement.
                mySqlCommand.CommandText = "INSERT INTO dbo.table1 (textBox1, textBox2) VALUES (@textBox1, @textBox2)";
                mySqlCommand.ExecuteNonQuery();
              }
            //Here you close the Reader and then dispose of the command.
            mySqlDataReader.Close();
            mySqlCommand.Dispose();
                //Normaly i would close the connection here but since i will be makeing
                //a SELECT right away to save the connection i will not close it just yet.
                //You acualy want to close the connection after every group of transaction
                //(don't waite for the user to do something to close the connection,
                //cuz if he just deside to close the browser the connection will stay open. for a long time...)
                //with the database, you don't want to leave it open othewise end users
                //will be put on holt untill the connection expires.
          //closeConn();

            //Now that the data was saved in the database we will do a select
            //from the database and set the text value of the label1 to texBox2.
     
           // Here we Create the connection to the Table.
            createConn("myDatabase");
            mySqlCommand = mySqlConnection.CreateCommand();
            mySqlCommand.CommandText = "SELECT * FROM dbo.table1 WHERE textBox1 = @textBox1";

            mySqlCommand.Parameters.Add("@textBox1", SqlDbType.VarChar);
            mySqlCommand.Parameters["@textBox1"].Value = TextBox1.Text;

            mySqlDataReader = mySqlCommand.ExecuteReader();
            //Here we use a "while" to set the value to the label
            while (mySqlDataReader.Read())
            {
                Label1.Text = Convert.ToString(mySqlDataReader["textBox2"]);
            }
            //Here you close the Reader and then dispose of the command adn the connection cuz we are done.
            mySqlDataReader.Close();
            mySqlCommand.Dispose();
            closeConn();
        }
    } 

     

    Simon Deshaies

    Support Specialist / Support C# Analyst at Nstein Technologies

    weblog.simondeshaies.net

    Please remember to click “Mark as Answer” on the post that helps you.


  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    12-13-2007, 12:03 AM

    HI Friends.

    IF You want to intrect any database in .NEt application . my best approach is ADO.NET . u wrote very un-professional code. Dont need worry about more Connection object .

     

     

    Rajeev Kumar Tiwari
  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    12-13-2007, 8:19 AM
    • Member
      144 point Member
    • Simon Deshaies
    • Member since 11-17-2007, 10:59 AM
    • Montr&#233;al, Canada
    • Posts 70

    rajeev.net@hotmail.com:

    HI Friends.

    IF You want to intrect any database in .NEt application . my best approach is ADO.NET . u wrote very un-professional code. Dont need worry about more Connection object .

    I guess that what you meant is that all my line breaks were missing? The forum played the trick on me when I clicked "Post" since this forum is moderated I could not edit until this morning.
    Simon Deshaies

    Support Specialist / Support C# Analyst at Nstein Technologies

    weblog.simondeshaies.net

    Please remember to click “Mark as Answer” on the post that helps you.


  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    02-04-2008, 2:11 AM
    • Member
      165 point Member
    • jack007
    • Member since 12-19-2007, 6:22 AM
    • Posts 588

    Hello,

    i dont know whether the above code is un-professional or not,since i m new to asp.net.

    anyway how would the code look like using ADO.net? as u mentioned

    it that it is more simple and professional.

    can u demonstrate with simple example along with code (C#).

    thanks.

    jack.
     

  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    02-04-2008, 8:08 AM
    Answer
    • Member
      144 point Member
    • Simon Deshaies
    • Member since 11-17-2007, 10:59 AM
    • Montr&#233;al, Canada
    • Posts 70
    Using ado.net would look like this. 
    
    This code sample was taken in the MSDN library at http://msdn2.microsoft.com/en-us/library/ms254507.aspx.
     

    C#

    // Assumes connectionString is a valid connection string.
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        // Do work here.
    }
     
    

    VB

    ' Assumes connectionString is a valid connection string.
    Using connection As New SqlConnection(connectionString)
        connection.Open()
        ' Do work here.
    End Using
    
    In this code sample you are missing allot of pieces per example you are not closing the connection.
    It's not reusing your existing connection ether. The code I posted uses ado.net and manages a lot of
    all you do not want to think about, take your time and study it.
     
    Simon Deshaies

    Support Specialist / Support C# Analyst at Nstein Technologies

    weblog.simondeshaies.net

    Please remember to click “Mark as Answer” on the post that helps you.


  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    02-04-2008, 8:22 AM
    Answer
    • Member
      144 point Member
    • Simon Deshaies
    • Member since 11-17-2007, 10:59 AM
    • Montr&#233;al, Canada
    • Posts 70

    I've refined the code above a bit and made a Class of it, here's the code. Just create a MySqlConnection.cs file in App_Code and paste the following code. If you are using a namespace just ad it.

    using System;
    using System.Data;
    using System.Data.Sql;
    using System.Data.SqlClient;

    ///
    <summary>
    /// This Class is specifically design to connect with optimized pooling to Microsoft Sql Server.
    /// </summary>
    public class MySqlConnection
    {
        public SqlConnection Connection;
        public SqlDataReader DataReader;
        public SqlCommand Command;
        private string mySqlConnectionString = "server=.\\SQLExpress;database=myDatabase;User ID=myDatabaseUser;Password=123456;Trusted_Connection=True;";
        public void CloseConn()
        {
            if (Connection != null)
            {
                if (Connection.State == ConnectionState.Open)
                {
                    Connection.Close();
                }
                Connection.Dispose();
            }
        }
        public SqlConnection CreateConn()
        {
            if (Connection == null) { Connection = new SqlConnection(); };
            if (Connection.ConnectionString == string.Empty || Connection.ConnectionString == null)
            {
                try
                {
                    Connection.ConnectionString = "Min Pool Size=5;Max Pool Size=40;Connect Timeout=4;" + mySqlConnectionString + ";";
                    Connection.Open();
                }
                catch (Exception)
                {
                    if (Connection.State != ConnectionState.Closed)
                    {
                        Connection.Close();
                    }
                    Connection.ConnectionString = "Pooling=false;Connect Timeout=45;" + mySqlConnectionString + ";";
                    Connection.Open();
                }
                return Connection;
            }
            if (Connection.State != ConnectionState.Open)
            {
                 try
                {
                    Connection.ConnectionString = "Min Pool Size=5;Max Pool Size=40;Connect Timeout=4;" + mySqlConnectionString + ";";
                    Connection.Open();
                }
                catch (Exception)
                {
                    if (Connection.State != ConnectionState.Closed)
                    {
                        Connection.Close();
                    }
                    Connection.ConnectionString = "Pooling=false;Connect Timeout=45;" + mySqlConnectionString + ";";
                    Connection.Open();
                }
            }
            return Connection;
        }
        public MySqlConnection()
        {

        }
    }

     

    Simon Deshaies

    Support Specialist / Support C# Analyst at Nstein Technologies

    weblog.simondeshaies.net

    Please remember to click “Mark as Answer” on the post that helps you.


  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    02-05-2008, 12:59 AM
    • Member
      165 point Member
    • jack007
    • Member since 12-19-2007, 6:22 AM
    • Posts 588

    Hi, 

     This Class is specifically design to connect with optimized pooling to Microsoft Sql Server.

     what does it mean??

     and why did u write so long code there? the above code is just for connection open and close write?

     plus why did u save it in app_code folder? any advantage?

     thanks.

      jack.
     

      

  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    02-05-2008, 8:01 AM
    Answer
    • Member
      144 point Member
    • Simon Deshaies
    • Member since 11-17-2007, 10:59 AM
    • Montr&#233;al, Canada
    • Posts 70

    The  MySqlConnection Class "Long Code" allows you to Create a connection to the database and close that connection, with pooling.

    Connecting to a database is the single slowest operation performed by a data-centric application. Reusing pooled connections, instead of creating new connections, can improve .NET application performance.

    You can control connection pooling behavior by using the connection string options set for your ADO.NET data provider:

    • Number of connection pools (Max Number of Pools)
    • Maximum connection pool size (Max Pool Size)
    • Minimum number of connections in a connection pool (Min Pool Size)
    • Number of seconds to keep connections in a connection pool (Connection Lifetime)

    The long code optimizes this pooling process and since it returns the connection it's able to verify if you already have an active connection.

    By having the long code in his own .cs in App_Code I can use it as a class. In my C# page I can initialize it like this MySqlConnection mySql = new MySqlConnection(); and then intellisence will give me the available Method and Object for this class by typing mySql.

    If you
    let me know how you want to use this or what you are trying to do, I will be able to give you more specific hints. 

    Simon Deshaies

    Support Specialist / Support C# Analyst at Nstein Technologies

    weblog.simondeshaies.net

    Please remember to click “Mark as Answer” on the post that helps you.


  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    02-06-2008, 12:07 AM
    • Member
      165 point Member
    • jack007
    • Member since 12-19-2007, 6:22 AM
    • Posts 588

     Hi Simon,

     Thanks for the explanation.

     since i m new to this field, i m very confused.

     there are many ways to connect to the sql database like sqldatasource(from design view),objectdatasource, ADO.net etc. 

     i  want to be familiar with just one standard method of insert,delete,update using sql and c#. 

     i m still not sure whether to use ur above code to accomplist the simple task like insert,delete,update etc.

      just little confused.

     thanks.

    jack.
     

      

  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    02-06-2008, 10:38 AM
    • Member
      144 point Member
    • Simon Deshaies
    • Member since 11-17-2007, 10:59 AM
    • Montr&#233;al, Canada
    • Posts 70

     Jack,

    The huge benefit of the code I suggest above it’s that it is fast, and optimizes your connection. Also it makes sure your connection will succeed and it reuses the same connection so you don’t end up with a bunch un unused active connection to your SQL.

    Because when you Open and Close a connection it stays in a kind of Sleep status where it waits to see if it will be reused, this process is probably thought to make it faster. The down side of this is if you have a total of 5 available connections to your SQL and you are using 1 and the 4 others are a Sleep your 6th connection attempt will take forever untill one of the Sleep is Disposed by SQL, you end up with a slow application even if all you code is top notch. Of course what I describe here in my knowledge only applies to Microsoft SQL 2000 and 2005, I just don’t know for the other SQL Servers.

    Have you tried to implement the MySqlConnection class to one of your projects?

    Simon Deshaies

    Support Specialist / Support C# Analyst at Nstein Technologies

    weblog.simondeshaies.net

    Please remember to click “Mark as Answer” on the post that helps you.


  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    02-06-2008, 1:33 PM
    • Member
      2 point Member
    • heroldjensen
    • Member since 02-06-2008, 6:18 PM
    • Posts 1

    Simon Deshaies:
    If you let me know how you want to use this or what you are trying to do, I will be able to give you more specific hints. 

     ... Hi

    I hope its ok i add a sub-question in this forum..

    Ive been searching for the answers ive found in this string all night, but still miss some.

    Ive been able to do a lot of the things i wish for using a sqldatasource, a detailsview, grid or other controls, but i am interested in creating the most optimal connection like described in this thread.

    Basically i want to design an input page, where a user creates a repair-case. The User id is successfully passed throug to this site from a customer overview page.

    So i have designed a page with repairtype, problem description, received by, etc etc..It includes textboxes and dropdownlists. + a submit repair button

    I understand all of the above, regarding creating a class for database connection which is optimized for pooling, but i dont know how to insert the data chosen/written in my textboxes to the table columns.

    Ive seen a lot of code examples but i seem a bit confused, and im searching the right way to do it. My best guess is that im missing code in my button_click event, and a insert <insert @

    But dont know how to write these. : / Any help would be appreciated..

     Lastly i wanna give a lot of credit to the forum, where a lot of my answers have been found, but still its the first time im posting, because of your posts about pooling, and connection class were so VERY helpful.

    Thanks

  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    02-06-2008, 2:34 PM
    • Member
      144 point Member
    • Simon Deshaies
    • Member since 11-17-2007, 10:59 AM
    • Montr&#233;al, Canada
    • Posts 70
    Heroldjensen,
    Well It’s a pleasure to know I’m helping, I’ve been there trying to do inserts, updates, delete and it’s hard until you understand how it’s done. If you have 2 text boxes here how it would go, in this example I assume that you are using MySqlConnection Class.

        protected void Button1_Click(object sender, EventArgs e)
        {
            MySqlConnection mySql = new MySqlConnection();
            mySql.CreateConn();
            mySql.Command = mySql.Connection.CreateCommand();
            mySql.Command.CommandText = "INSERT INTO dbo.table1 (textBox1, textBox2) VALUES (@textBox1, @textBox2)";
            
            
    mySql.Command.Parameters.Add("@textBox1", SqlDbType.VarChar);
            mySql.Command.Parameters["@textBox1"].Value = TextBox1.Text;
            mySql.Command.Parameters.Add("@textBox2", SqlDbType.VarChar);
            mySql.Command.Parameters["@textBox2"].Value = TextBox2.Text;

            mySql.Command.ExecuteNonQuery();
     
            mySql.Command.Dispose();
            mySql.Connection.Close();
            mySql.CloseConn();
        }


     This is the easy “Simple” way, you can also use a stored procedure that makes everything faster and way cooler. To learn about stored procedure I recommend the Bob Tabor video in the Learn ==> SQL section.

     

    Simon Deshaies

    Support Specialist / Support C# Analyst at Nstein Technologies

    weblog.simondeshaies.net

    Please remember to click “Mark as Answer” on the post that helps you.


  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    03-23-2008, 1:19 PM
    • Member
      144 point Member
    • Simon Deshaies
    • Member since 11-17-2007, 10:59 AM
    • Montr&#233;al, Canada
    • Posts 70

    UPDATED! 
    Since I initially wrote this how to I’ve improved the integration of this class quite a bit, you may read the new how to here, and get the revised sample here.

    Simon Deshaies

    Support Specialist / Support C# Analyst at Nstein Technologies

    weblog.simondeshaies.net

    Please remember to click “Mark as Answer” on the post that helps you.


  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    05-14-2008, 9:38 AM
    • Member
      524 point Member
    • oguzkaygun
    • Member since 04-27-2008, 12:44 PM
    • Posts 1,256

     

    hello

    i come here to want to help from you :) i use visual basic for visual web developer

    i have database.mdf and table1 in database.mdf.. table1 has user and productname.. both of them is coulumname.. both of them datatype is nchar

    also i have gridview1 and sqldatasource1 and textbox1 and textbox2.. i want gridview to display items that user = textbox1.text and productname = textbox2.text

    i want to use select command and conn.open and conn.close and other sqlcommands :)

    could you write to me as visual basic code ?

    cheers

    Mark as me if my question or my answer can be helpful for you :)
  • Re: How To: Connect to SQL using C# and SELECT INSERT UPDATE ?

    05-14-2008, 11:10 AM
    • Member
      144 point Member
    • Simon Deshaies
    • Member since 11-17-2007, 10:59 AM
    • Montr&#233;al, Canada
    • Posts 70

    oguzkaygun,

    This is a tad unusual, I don’t write Visual Basic. You should consider learning C#, I believe it's going to be around longer. But what I can do is point you to a C# ~ VB converter http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx will allow you to convert my example to VB. In the C# example I already demonstrate how to do what you are trying to do.


    Regards,
    Simon Deshaies

    Support Specialist / Support C# Analyst at Nstein Technologies

    weblog.simondeshaies.net

    Please remember to click “Mark as Answer” on the post that helps you.


Page 1 of 4 (54 items) 1 2 3 4 Next >