Connection to the MS SQL Database in C#

Asked By 0 points N/A Posted on -
qa-featured

I am new to C#.Net I need to know how to connect MS SQL Database using C# language.

Please describe the process.

SHARE
Best Answer by Mcclain Prins
Answered By 0 points N/A #157589

Connection to the MS SQL Database in C#

qa-featured

Well,

When you are going to use SQL with C# coding the very first thing you have to do is import the name spaces.

You have to import following components.

using System.Data.SqlClient;

Then in the coding section you have to write this code to connect with the database.

try
{
               SqlConnection myCon = new SqlConnection(@"<connection string>");
               //myCon is the sqlConnection type variable.

             myCon.Open()
            //this is how the created connection is opened

           //
           //
           //Use these lines to write other codes that you need to write.
           //
           //

           myCon.Close()
         //This is how the close an opened connection.
}
Catch
{
         messageBox.Show(“The database connectivity has an error”)
}

(The try catch block is not mandatory)

Best Answer
Best Answer
Answered By 5 points N/A #157590

Connection to the MS SQL Database in C#

qa-featured

Hello Richad

You can connect MS SQL using LINQ easily from C#. For this you have to follow the following steps.

1. Right click on your Project   Add > New Item > "Linq to SQL Classes"  , named the file as connect.dbml( for example).

2. Create connection with SQL Server in Connect.dbml file. Add list of tables you want to add in your project to perform DB operation

3.   Now you are ready to connect SQL Server with LINQ. Here is the code Snippet for you

       connectDataContext db = new connectDataContext();

     db.Connection.ConnectionString = [ CONNECTION STRING] ;

     db.[TABLE OR PROCEDURE NAME] ( {PARAMETER}) ;

     db.SubmitChanges();

Now you are connected with SQL Server.

Hope this would help

Related Questions