Hi guys,
I'm a newbie at .NET/C#. How do I make a database connection to SQL Server in C# ?
A sample code in C# will be appreciated.
Thanks.
Tommy
Loading
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 attend4days leftRegister
Del Woodcock67 reputationPosted Apr 20, 2012, 12:50 PM EDT
Note: Your server will need a different connection string, see http://www.connectionstrings.com/
var sqlConn = new SqlConnection("Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True");
try
{
var sqlCmd = new SqlCommand
{
CommandText = string.Format("SELECT aaa, bbb, ccc FROM myDataBase WHERE aaa='{0}'", whatever),
CommandType = CommandType.Text,
Connection = sqlConn
};
sqlConn.Open();
var sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
aaa = (int)sqlReader[0];
bbb = (bool)sqlReader[1];
ccc = sqlReader[2].ToString();
console.writeline(string.format("{0}, {1}, {2}", aaa, bbb, ccc);
}
sqlReader.Close();
}
catch (Exception ex)
{
MessageBox.Show(string.Format("SQL Error:\r\n\r\n{0}", ex.Message), "SQL Error - xxx");
}
finally
{
sqlConn.Close();
}
Tommy4 reputationPosted Apr 20, 2012, 1:56 PM EDT
brunda kRank #3,804 · 389 reputationPosted Apr 21, 2012, 12:20 AM EDT
HKEY_LOCAL_MACHINE/Software/Microsoft/MicrosoftSqlServer/InstalledInstances
Sam HobbsRank #107 · 20.5K reputationPosted Apr 22, 2012, 10:27 AM EDT
I also suggest not asking the same question more than once at the same time. This is the same as your How to create a SQL Server database in Visual Studio.NET ? which also has replies. People that volunteer their time to help others do not appreciate answering questios that have already been answered elsewhere and that it is true for all forums in all web sites.
There are also many articles in this web site that can help you.
The best way to create a database connection is to use the Data Sources window. When you do that, Visual Studio will create a connection string for you and put in a property setting for your project. It will also generate some code for you. Note that when you do this, you will have a choice of Database, Service, Object or Sharepoint; choose Database of course. Then in the next property page, you will have a choice of either Dataset or Entity Data Model. If you choose Dataset then it will create a TableAdpapter as described in my article but TableAdpapters are older technology. The Entity Data Model is newer technology. Look for articles in this web site for more help.
Del Woodcock67 reputationPosted Apr 23, 2012, 6:58 AM EDT