C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: This connection string is often generated for you by the dialogs in Visual Studio, and is sometimes provided by a host.
And: 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.
//
con.Open();
//
// This 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));
}
}
}
}
}
Output
57 Koko Shar Pei
130 Fido Bullmastiff
Add new data source: 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.
Internally: The language can transform the using statement into a try-finally statement that calls the Dispose method.
UsingAnd: The SqlConnection is passed as the parameter to the SqlCommand. In this way we specify that the SqlCommand "uses" the SqlConnection.
And: 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 reliably use the using statement.
SqlConnection: Microsoft Docs