C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ADO.NET SqlConnection ClassIt is used to establish an open connection to the SQL Server database. It is a sealed class so that cannot be inherited. SqlConnection class uses SqlDataAdapter and SqlCommand classes together to increase performance when connecting to a Microsoft SQL Server database. Connection does not close explicitly even it goes out of scope. Therefore, you must explicitly close the connection by calling Close() method. SqlConnection Signaturepublic sealed class SqlConnection : System.Data.Common.DbConnection, ICloneable, IDisposable SqlConnection Constructors
SqlConnection Methods
SqlConnection ExampleNow, let's create an example that establishes a connection to the SQL Server. We have created a Student database and will use it to connect. Look at the following C# code. using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); } Using block is used to close the connection automatically. We don't need to call close () method explicitly, using block do this for ours implicitly when the code exits the block. // Program.cs using System; using System.Data.SqlClient; namespace AdoNetConsoleApplication { class Program { static void Main(string[] args) { new Program().Connecting(); } public void Connecting() { using ( // Creating Connection SqlConnection con = new SqlConnection("data source=.; database=student; integrated security=SSPI") ) { con.Open(); Console.WriteLine("Connection Established Successfully"); } } } } Output: What, if we don't use using block. If we don't use using block to create connection, we have to close connection explicitly. In the following example, we are using try-block instead of using block. // Program.cs using System; using System.Data.SqlClient; namespace AdoNetConsoleApplication { class Program { static void Main(string[] args) { new Program().Connecting(); } public void Connecting() { SqlConnection con = null; try { // Creating Connection con = new SqlConnection("data source=.; database=student; integrated security=SSPI"); con.Open(); Console.WriteLine("Connection Established Successfully"); } catch (Exception e) { Console.WriteLine("OOPs, something went wrong.\n"+e); } finally { // Closing the connection con.Close(); } } } } Output:
Next TopicADO.NET Command
|