DB Connection Of SQL server 2008 to MS visual c# 2010 ?
How to connect SQL server express 2008 to MS visual c# 2010 and how retrieve data from SQL Server through Visual C# console Application?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sunny SharmaRank #223 · 11.1K reputationPosted Jun 13, 2013, 10:29 PM EDT
To achieve this purpose, you will have to use the classes inside System.Data namespace. Add a reference if haven't done yet. In the sample code below I have used the connection string for my local database, you can find other syntax and formats of connection string as well at:
http://connectionstrings.com/sql-server-2008
Below are the sample code for you on how to access data... :
-------------------------------------------------------------
string ConStr = "Server=SUNNY-PC\\SQLEXPRESS;Database=students;Integrated Security=true;";
SqlConnection MyCon = new SqlConnection(ConStr);
SqlCommand cmd = new SqlCommand("select * from students", MyCon);
try
{
MyCon.Open();
}
catch(Exception ex)
{
Console.WriteLine("Database connection error: " + ex.Message);
}
if (MyCon.State == ConnectionState.Open)
{
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("******** NAMES **********");
while (reader.Read())
{
// do whatever you want here with data. You can also use SqlDataAdapter to fill in a DataTable instead of using SqldataReader
Console.WriteLine(reader.GetString(1));
}
Console.WriteLine("--------- ****** -----------");
}
if (MyCon.State == ConnectionState.Open)
{
try
{
MyCon.Close();
}
catch { }
}
--------------------------------------------------------------------
Reply back for any clarification.
Please don't forget to mark this as answer if it helps :)
Thanks.