This article, provides a basic example, on how to establish a connection to SQL Server from a C# program with the use of the “using” statement in C# which help you better managing your database connections.
Using the System.Data.SqlClient
Use the System.Data.SqlClient namespace in the top section of your code as below:
using System.Data.SqlClient;
Setting the Connection String
Set the connection string – Trusted connection (Windows Authentication). In the below example I’m using “master” as the default database. You can replace “master” with the default database you wish to set:
string connString = @"Server=INSTANCE_NAME;Database=master;Trusted_Connection = True;";
Get Started with .NET Programming Fast and Easy – Enroll to the Online Course!
Check our online course titled “.NET Programming for Beginners: Windows Forms (C#)“
(special limited-time discount included in link).Learn how to implement Windows Forms projects in .NET using Visual Studio and C#, how to implement multithreading, how to create deployment packages and installers for your .NET Windows Forms apps using ClickOnce in Visual Studio, and more!
Many live demonstrations and downloadable resources included!
In case you want to set a connection string with standard security (username/password – not recommended) then you can set the connection string based on the below example:
string connString = @"Server=INSTANCE_NAME;Database=master;User ID=USERNAME;Password=PASSWORD";
The “Using” Keyword in C#
With the “using” keyword, .NET automatically manages the task of closing the connection to the database. This an easy way to avoid “connection leak” issues. Here’s the code example:
using (SqlConnection conn = new SqlConnection(connString)) { //set the command to execute against SQL Server (this is where you set your query) string query = @"SELECT[fileid],[filename] FROM sysfiles"; SqlCommand cmd = new SqlCommand(query, conn); //open connection conn.Open(); //the actual command execution SqlDataReader dr = cmd.ExecuteReader(); //if reader has any rows retrieve them if (dr.HasRows) { while (dr.Read()) { //handle the retrieved record (i.e. display it) MessageBox.Show(dr.GetInt16(0) + " – " + dr.GetString(1)); } } else { MessageBox.Show("No data found."); } dr.Close(); }
Additional resources:
Featured Online Courses:
- SQL Server 2022: What’s New – New and Enhanced Features
- Data Management for Beginners – Main Principles
- Introduction to Azure Database for MySQL
- Working with Python on Windows and SQL Server Databases
- Boost SQL Server Database Performance with In-Memory OLTP
- Introduction to Azure SQL Database for Beginners
- Essential SQL Server Administration Tips
- SQL Server Fundamentals – SQL Database for Beginners
- Essential SQL Server Development Tips for SQL Developers
- Introduction to Computer Programming for Beginners
- .NET Programming for Beginners – Windows Forms with C#
- SQL Server 2019: What’s New – New and Enhanced Features
- Entity Framework: Getting Started – Complete Beginners Guide
- A Guide on How to Start and Monetize a Successful Blog
- Data Management for Beginners – Main Principles
Read Also:
- How to Set Filters for OpenFileDialog and SaveFileDialog in C#
- .NET Programming for Beginners – Windows Forms (C#)
- There is no argument given that corresponds to the required formal parameter
- The timeout period elapsed prior to obtaining a connection from the pool
- Closing a C# Application (including hidden forms)
- Changing the startup form in a C# project
- Using the C# SqlParameter Object for Writing More Secure Code
- Cannot implicitly convert type ‘string’ to ‘System.Windows.Forms.DataGridViewTextBoxColumn
- Using the C# SqlParameter Object for Writing More Secure Code
- Tip of the Week No.15 – Main Data Structures in C#
- How to Build a Simple Image Viewer with .NET WinForms and C# in Visual Studio
Did you find this article useful and interesting?
Check our other related .NET articles.
Check out our latest software releases!
Subscribe to our newsletter and stay up to date!
Rate this article:
Reference: SQLNetHub.com (https://www.sqlnethub.com)
© SQLNetHub
Artemakis Artemiou, a distinguished Senior Database and Software Architect, brings over 20 years of expertise to the IT industry. A Certified Database, Cloud, and AI professional, he earned the Microsoft Data Platform MVP title for nine consecutive years (2009-2018). As the founder of SQLNetHub and GnoelixiAI Hub, Artemakis is dedicated to sharing his knowledge and democratizing education on various fields such as: Databases, Cloud, AI, and Software Development. His commitment to simplicity and knowledge sharing defines his impactful presence in the tech community.