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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sunny SharmaPosted Jun 14, 2013, 2:29 AM
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.