Connection to the MS SQL Database in C#
I am new to C#.Net I need to know how to connect MS SQL Database using C# language.
Please describe the process.
I am new to C#.Net I need to know how to connect MS SQL Database using C# language.
Please describe the process.
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)
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