Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# SqlConnection Example: Using, SqlCommand

This C# program uses SqlConnection. It requires System.Data.SqlClient.

SqlConnection. The SqlConnection class handles database connections.

It initiates a connection to your SQL database. This class is best used in a using resource acquisition statement. We call Open to query the database with SqlCommand.


Example. We emphasize the usage of SqlConnection in a "using" resource acquisition statement. The SqlConnection has a constructor that requires a string reference pointing to the connection string character data.

This connection string is often autogenerated for you by the dialogs in Visual Studio, and sometimes is provided by your hosting company or department. You must include the SqlConnection code before you can perform a database query.

C# program that uses SqlConnection

using System;
using System.Data.SqlClient;

class Program
    static void Main()
	// First access the connection string.
	// ... This may be autogenerated in Visual Studio.
	string connectionString = ConsoleApplication1.Properties.Settings.Default.ConnectionString;
	// In a using statement, acquire the SqlConnection as a resource.
	using (SqlConnection con = new SqlConnection(connectionString))
	    // Open the SqlConnection.
	    // The following code uses an SqlCommand based on the SqlConnection.
	    using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
	    using (SqlDataReader reader = command.ExecuteReader())
		while (reader.Read())
		    Console.WriteLine("{0} {1} {2}",
			reader.GetInt32(0), reader.GetString(1), reader.GetString(2));


57 Koko Shar Pei
130 Fido Bullmastiff

This program will not work unless you change the connection string reference to point to a correct one in your environment. To create a connection string to a database, go to the Visual Studio Data menu and select Add New Data Source.

Also: The program assumes the name of an SQL table that will not be present in most databases.

Using statement. The purpose of the using statement in the C# language is to provide a simpler way to specify when the unmanaged resource is needed by your program, and when it is no longer needed.

Internally: The language can transform the using statement into a try-finally statement that calls the Dispose method.



Open method call. The using statement creates a read-only variable of type SqlConnection. You need to actually call the Open method on the SqlConnection instance before using it in an actual SqlCommand.

And: The SqlConnection is passed as the parameter to the SqlCommand. In this way we specify that the SqlCommand "uses" the SqlConnection.

Tutorial. For the example to work correctly, it would need to find the specified SQL table. The specified connection string must be correct. This site contains a more thorough overview and tutorial of SqlConnection and its supporting constructs.

SqlClient Tutorial: SqlConnection, SqlCommand

Using. In the annotated C# language specification, we are advised to use the "using" statement when creating any object that implements the interface IDisposable. Even if the interface does nothing, it is safest to always call it if it exists.

Note: Many examples of SqlConnection and SqlCommand do not use the using statement reliably, including the one on MSDN.

SqlConnection: MSDN

Summary. We looked at database code. We stressed the proper usage of the SqlConnection class and the resource acquisition pattern. The SqlConnection is required for correctly using other SQL objects such as SqlCommand and SqlDataReader.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf