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.
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.
Del WoodcockPosted Apr 23, 2012, 10:58 AM
Sam HobbsPosted Apr 22, 2012, 2:27 PM
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.
brunda kPosted Apr 21, 2012, 4:20 AM
HKEY_LOCAL_MACHINE/Software/Microsoft/MicrosoftSqlServer/InstalledInstances
TommyPosted Apr 20, 2012, 5:56 PM
Del WoodcockPosted Apr 20, 2012, 4:50 PM
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();
}