Introduction to ADO.NET |
|
Microsoft SQL Server and Microsoft Visual Studio 2022
Introduction
Microsoft SQL Server is mainly used to create and maintain computer databases. It does not provide the means of creating graphical elements that would make it easy for a regular user to take advantage of its databases. To create an application made of graphical user interface (GUI) objects, you must use a separate environment. To make this easy, Microsoft created a very direct link between Microsoft Visual Studio and Microsoft SQL Server. The communication is so smooth that, from Microsoft Visual Studio, you can use Microsoft SQL Server directly without having to formally open the database server.
Introduction to ADO.NET
ADO.NET is a group of libraries used to create powerful databases using various sources that include Microsoft SQL Server, Microsoft Access, Oracle, XML, etc. ADO.NET relies on the .NET Framework's various classes to process requests and ensure the interaction between a database system and the user. The operations are typically handled through the DataSet class.
While ADO.NET is the concept of creating and managing database systems, the DataSet class serves as an intermediary between the database engine and the user interface, namely the Windows controls that the user uses to interact with the computer. Still, remember that a DataSet object is used to manage lists, any lists, not just those created using a database environment. Besides using features of a database in an ADO.NET application, you can also fully take advantage of XML as it is completely and inherently supported by the DataSet class. To fully support XML in your application, we know that the .NET Framework is equipped with the System.Xml.dll library.
Getting Access to ADO.NET Libraries |
The classes used to create ADO.NET databases are defined in the System.Data namespace and are stored in the System.Data.dll library. If you create a Windows Forms Application from the New Project dialog box, Microsoft Visual Studio would automatically include the System.Data.dll library and add the System.Data namespace to your project, even if you are not creating a database application. This makes it convenient.
If you are creating the application from scratch, in order to use ADO.NET, you must add a reference to the System.Data.dll library and add the System.Data namespace in your file(s).
Overview |
To perform an operation on a database server, you must establish a connection to it. Microsoft Visual Studio 2013 provides many options. To start, you must have a version of Microsoft SQL Server 2012 installed on your computer. You can download and install a trial version of Microsoft SQL Server 2012 (or 2014) Enterprise from the Microsoft Web site (http://www.microsoft.com/en-us/sqlserver/default.aspx) or another version (Microsoft SQL Server Developer, Enterprise, Express, LocalDb, or Compact). After installing a version of Microsoft SQL Server, there are various (or different) ways to use each.
To be as flexible as possible, ADO.NET allows you to work with various types of databases. This also means that when you create an application. You must certainly first specify the type of database system you would be using. As mentioned already, you have many options in Microsoft Visual Studio to establish a connection:
After making your selection, click Continue. This would open the Add Connection dialog box:
Introduction to the SQL Connection |
A Class for a SQL Connection |
To support a connection to Microsoft SQL Server, the .NET Framework provides the SqlConnection class:
public sealed class SqlConnection : DbConnection, ICloneable
The SqlConnection class is defined in the System.Data.SqlClient namespace. Before using this class, you can first include this namespace in your file:
using System; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; public class Exercise : Form { public Exercise() { InitializeComponent(); } private void InitializeComponent() { Text = "Introduction to ADO.NET"; StartPosition = FormStartPosition.CenterScreen; } static int Main() { System.Windows.Forms.Application.Run(new Exercise()); return 0; } }
To connect to a database, you can first declare a variable of type SqlConnection using one of its two constructors. The default constructor allows you to declare the variable without specifying how the connection would be carried.
The second constructor takes as argument a string value. Its syntax is:
public SqlConnection(string connectionString);
You can create the necessary (but appropriate) string in this constructor when declaring the variable. This would be done as follows:
public class Exercise : Form { public Exercise() { InitializeComponent(); } void InitializeComponent() { SqlConnection connection = new SqlConnection("Something"); } }
If you want, you can first create the string that would be used to handle the connection, then pass that string to this construction. This would be done as follows:
void InitializeComponent() { string strConnection = "Something"; SqlConnection connection = new SqlConnection(strConnection); }
Introduction to the Connection String |
If you are not connecting to the server using a dialog box, you must provide a collection of values and that collection is called a connection string. To support the connection as an object, the SqlConnection class is equipped with a property called ConnectionString, which is a string. If you use the default constructor to prepare the connection, you can first define a string value, then assign it to this property. This would be done as follows:
void InitializeComponent() { string strConnection = "Something"; SqlConnection connection = new SqlConnection(); connection.ConnectionString = strConnection; }
The Attributes of a Connection String |
To use a SqlConnection object, you must provide various pieces of information, packaged as one and made available to the variable. These pieces of information are joined into a string but are separated from each other with a semi-colon ";". Each piece appears as a Key=Value format. In our lessons, we will refer to each of these pieces (Key=Value) as an attribute of the connection string. When joined, these attributes appear as follows:
Key1=Value1;Key2=Value2;Key_n=Value_n
Anything that is part of this string is not case-sensitive (even though you are working on a C# application). This whole group is either passed as a string to the second constructor:
void InitializeComponent() { SqlConnection connection = new SqlConnection("Key1=Value1;Key2=Value2;Key_n=Value_n"); }
or assigned as a string to the SqlConnection.ConnectionString property:
void InitializeComponent() { string strConnection = "Key1=Value1;Key2=Value2;Key_n=Value_n"; SqlConnection connection = new SqlConnection(); connection.ConnectionString = strConnection; }
How you create these attributes depends on the type of computer you are connecting to, whether you are connecting to a database, what level of security you would use (or need), etc. There are various of these attributes, some of them are always required, some of them are usually optional, and some others depend on the circumstances.
The Connection String Builder |
As seen above, you can provide all the parts of a connection string in one string. Alternative, to assist you with creating a connection string, the System.Data.SqlClient namespace of the .NET Framework provides a class named SqlConnectionStringBuilder that is derived from a class named DbConnectionStringBuilder:
public sealed class SqlConnectionStringBuilder : DbConnectionStringBuilder
The DbConnectionStringBuilder class starts as follows:
public class DbConnectionStringBuilder : IDictionary, ICollection, IEnumerable, ICustomTypeDescriptor
As you can see, the DbConnectionStringBuilder class is a collection class that implements the IDictionary and the ICollection interfaces. Since this class implements a dictionnary, this means that its members are of type Key=Value. This also means that the class inherits a property named Item that makes it possible to access members using an indexed property passed by name.
Since this class implements ICollection, this means that it can add, remove, and insert items.
The SqlConnectionStringBuilder class has two constructors. If you already have a connection string, you can pass it to the following constructor:
public SqlConnectionStringBuilder(string connectionString);
To create a connection string from scratch, use the default constructor.
The Source of Data |
To establish a connection, you must specify the computer you are connecting to, that has Microsoft SQL Server installed. You can specify this from the Connect to Server dialog box where you would select the machine from the Server Name combo box. If you are working from the Add Connection dialog box, to see the list of servers and select one, you can click the arrow of the Server Name combo box. If you are working from the Add Connection dialog box, you can type (local) in the Server Name combo box.
If you are programmatically connecting to a computer using the SqlConnection class, the connection string includes an attribute named Server, or Data Source, or Address, or Addr, or Network Address. For the rest of our lessons, this attribute will be referred to as the computer attribute. If you are creating your connection string using the SqlConnectionStringBuilder class, it is equipped with a property named DataSource, which is a string:
public string DataSource { get; set; }
If you are creating your application on the same computer on which Microsoft SQL Server is installed, the computer attribute can be identified as (local). Here is an example that uses the SqlConnection class:
void InitializeComponent() { SqlConnection connection = new SqlConnection("Server=(local); "); }
Here is an example that uses the SqlConnectionStringBuilder class:
void CreateConnection() { SqlConnectionStringBuilder csbExercise = new SqlConnectionStringBuilder(); csbExercise.DataSource = "(local);"; }
Remember that the SqlConnectionStringBuilder class inherits an indexed property. This makes it possible to access a property, such as DataSource, by name. Here is an example:
void CreateConnection() { SqlConnectionStringBuilder csbExercise = new SqlConnectionStringBuilder(); csbExercise["DataSource"]; }
If you know the name of the computer, you can assign it to the computer attribute. Here is an example that uses the SqlConnection class:
void InitializeComponent() { SqlConnection connection = new SqlConnection("Server=YellowCastle; "); }
In the same way, if you are connecting to a specific computer, you must provide its name. Here is an example that uses the SqlConnection class:
SqlConnection connection = new SqlConnection("Data Source=YellowCastle; ")
Here is an example that uses the SqlConnectionStringBuilder class:
void CreateConnection() { SqlConnectionStringBuilder csbExercise = new SqlConnectionStringBuilder(); csbExercise.DataSource = "YellowCastle;"; }
As an option, you can include the name of the computer in single-quotes.
Fundamentals of Authentication
Introduction
An important aspect of establishing a connection to a computer is security. Even if you are developing an application that would be used on a standalone computer, you must take care of this issue. The security referred to in this attribute has to do with the connection, not how to protect your database.
If you are working in the Add Connection dialog box, if you wan to use the account that opened the application, you can accept the Windows Authentication radio button. If you want to specify the authentication, click the Use SQL Server Authentication:
If you are programmatically establishing the connection, the connection string of the SqlConnection class includes an attribute called Trusted_Connection or Integrated Security that can have a value of true, false, yes, no, or SSPI with the SSPI having the same indication as true. If you are creating your connection string using the SqlConnectionStringBuilder class, it is equipped with a Boolean property named IntegratedSecurity:
public bool IntegratedSecurity { get; set; }
If you are establishing a trusted or simple connection that doesn't need to be verified, you can assign a value of true or SSPI. Here is an example:
void InitializeComponent() { SqlConnection connection = new SqlConnection("Server=(local);Trusted_Connection=SSPI"); }
When you use the true or SSPI values, the user name (if any) and the password (if any) of the person opening your application would be applied. For example, if the application is being opened on Microsoft Windows 7 Professional, Ultimate, Enterprise, or Windows 8 Pro that has a default user name and password, the application would be opened fine without checking security.
If you are programmatically establishing the connection, to apply authentication, you can assign false or no to the security attribute you selected. Here is an example:
void InitializeComponent() { SqlConnection connection = new SqlConnection("Server=(local);Integrated Security=no"); }
The User ID |
If you are using the Add connection dialog box and if you had clicked the Use SQL Server Authentication radio button, type the user name in the User Name text box. When you are programmatically connecting to a server and you are using the SqlConnection, use the User ID attribute to provide a username. If you are using the SqlConnectionStringBuilder class, it is equiped with a property named UserID, which is a string:
public string UserID { get; set; }
Here is an example of using it:
void CreateConnectionString()
{
SqlConnectionStringBuilder csbExercise = new SqlConnectionStringBuilder();
csbExercise.DataSource = "(local)";
csbExercise.UserID = "Admin";
}
The Password |
When you are establishing a connection to a server, besides the username, to specify the password, if you are using the Add connection dialog box and if you had clicked the Use SQL Server Authentication radio button, after typing a user name in the User Name text box, type the corresponding password in the other text box. If yo are using SQL code, use either the PASSWORD or the PWD (remember that the attributes are not case-sensitive but the value of the password is) attribute and assign it the exact password associated with the User ID attribute of the same connection string. Here is an example:
void InitializeComponent() { string strConnection = "Server=(local);" + "Integrated Security=no;" + "User ID=wmessmann;PWD=$outh~@kotA"; SqlConnection connection = new SqlConnection(strConnection); }
In some circumstances, you can use an empty password in which case you would assign an empty string to the password attribute. If you are using the SqlConnectionStringBuilder class, it is equipped with a property named Password:
public string Password { get; set; }
You can then assign a password to this property.
The Database |
If you are working from the Add Connection dialog box, if you want to establish a connection to a specific database, click the arrow of the Select Or Enter A Database Name combo box and select the desired database. If you are working programmatically, to let you specify the database, the connection string includes an attribute named Database. The Database attribute allows you to specify the name of the database you are connecting to, if any. The Database keyword can also be substituted for the Initial Catalog value. If you are connecting to an existing database, assign its name to this attribute. If you are not connecting to a database, you can omit this attribute. Alternatively, you can assign nothing to this attribute. Here is an example:
void InitializeComponent() { SqlConnection connection = new SqlConnection(Server=(local);Database=;); }
Another alternative is to assign an empty, single-quoted, string to this attribute. Here is an example:
void InitializeComponent() { string strConnection = "Server=(local);Initial Catalog='exercise1';"; SqlConnection connection = new SqlConnection(strConnection); }
As mentioned above, the Database attribute is optional, especially if you are only connecting to the computer and not to a specific database. If you are using the SqlConnectionStringBuilder class, it is equipped with a property named InitialCatalog:
public string InitialCatalog { get; set; }
You can assign the name of the database to this property.
Additional Attributes |
There are various other attributes used in the connection string. They include Network Library (also called Net), Application Name, Workstation ID, Encrypt, Connection Timeout, Data Source, Packet Size, AttachDBFilename, Current Language, Persist Security Info.
After creating the connection string, when the application executes, the compiler would "scan" the string to validate each key=value section. If it finds an unknown Key, an unknown value, or an invalid combination of key=value, it would throw an ArgumentException exception and the connection cannot be established.
Opening and Closing a Connection |
Opening a Connection |
If you are using the Add Connection dialog box, after specifying the necessayr pieces of information, to open the connection, click OK. If you are writing code, to open the connection, you must call the SqlConnection.Open() method. Its syntax is:
public override void Open();
Here is an example of calling it:
void InitializeComponent() { SqlConnection connection = new SqlConnection("Server=(local);Initial Catalog='exercise1';"); connection.Open(); }
As you can see, this method does not take any argument. The SqlConnection object that calls it is responsible to get the connection string ready:
Closing or Deleting a Connection |
If you are working from a SqlConnection object, to close a connection, you can call the SqlConnection.Close() method. Its syntax is:
public virtual void Close();
This method is simply called to close the current connection. Here is an example of calling it:
void InitializeComponent() { SqlConnection connection = new SqlConnection("Server=(local);Initial Catalog='exercise1';"); connection.Open(); // Do some things here connection.Close(); }
While you should avoid calling the Open() method more than once if a connection is already opened, you can call the Close() method more than once.
Disposing of a Connection |
The SqlConnection class is derived from a class named DbConnection:
public abstract class DbConnection : Component, IDbConnection, IDisposable
As you can see, the DbConnection class implements the IDisposable interface. This means that, to close the connection and free its resources, you can use the using keyword. This would be done as follows:
void InitializeComponent() { using (SqlConnection connection = new SqlConnection("Data Source=(local);Integrated Security=yes")) { conDatabase.Open(); } }
When this code executes, it opens the connection. Inside of the curly brackets, you can do whatever you want. When the compiler reaches the closing curly bracket, it calls the SqlConnection.Close() method, which means you do not need to remember to close it.
Commanding a Database |
Introduction |
After establishing a connection, if you are successful, the database system becomes available to you and you can take actions, such as creating a database and/or manipulating data. An action you perform on the database server or on a database is called a command.
To support the various commands you can perform on a Microsoft SQL Server database, the System.Data.SqlClient namespace provides the SqlCommand class. To use it, you can declare a variable of type SqlCommand using one of its constructors.
The Text to Command |
The SqlCommand class is equipped with four constructors. The default constructor allows you to initiate a command without specifying what action would be taken. The action to perform is created as a string statement. This action is represented by the CommandText property of the SqlCommand class, which is of type string.
If you want to use the default constructor, you can then create a string that would carry the action to perform. Once the string is ready, you can assign it the CommandText property. This would be done as follow:
void InitializeComponent() { SqlCommand CommandToExecute = new SqlCommand(); string strCommandToExecute = "Blah Blah Blah"; CommandToExecute.CommandText = strCommandToExecute; }
After creating the action that would be performed, you must specify what connection would carry it. To do this, you can first create a SqlConnection object. To provide it to the command, the SqlCommand class is equipped with a property named Connection that is of type SqlConnection. After creating a SqlConnection object, to provide it to the command, you can assign it to the SqlCommand.Connection property. This would be done as follows:
void InitializeComponent() { string strConnection = "Server=(local);" + "Integrated Security=no;" + "User ID=sa;PWD=$outh~@kotA"; SqlConnection connection = new SqlConnection(strConnection); SqlCommand CommandToExecute = new SqlCommand(); string strCommandToExecute = "Blah Blah Blah"; connection.Open(); CommandToExecute.Connection = connection; CommandToExecute.CommandText = strCommandToExecute; connection.Close(); }
Instead of declaring a SqlCommand variable and the command text separately, as an alternative, you can define the command text when declaring the SqlCommand variable. To do this, you can use the second constructor of the SqlCommand class. The syntax of this constructor is:
public SqlCommand(string cmdText);
Once again, after using this constructor, you must specify what connection would carry the action. To do this, you can assign a SqlConnection object to the Connection property of your SqlCommand. Here is an example:
void InitializeComponent() { string strConnection = "Server=(local);" + "Integrated Security=no;" + "User ID=sa;PWD=$outh~@kotA"; SqlConnection connection = new SqlConnection(strConnection); SqlCommand CommandToExecute = new SqlCommand("Blah Blah Blah"); connection.Open(); CommandToExecute.Connection = connection; connection.Close(); }
Instead of assigning a SqlConnection object to the SqlCommand.Connection property, you can specify what connection would carry the action at the same time you are creating the command. To specify the connection when declaring the SqlCommand variable, you can use the third constructor of this class. Its syntax is:
public SqlCommand(string cmdText, SqlConnection connection);
The second argument to this constructor is an established connection you would have defined. Here is an example:
void InitializeComponent() { SqlConnection connection = new SqlConnection("Server=(local);" + "Integrated Security=no;" + "User ID=sa;PWD=$outh~@kotA"); SqlCommand CommandToExecute = new SqlCommand("Blah Blah Blah", connection); connection.Open(); CommandToExecute.Connection = connection; connection.Close(); }
If you had initiated the action using the default constructor of the SqlCommand class, you can assign a SqlConnection object to the Connection property of the SqlCommand class.
In the next sections and future lessons, we will study the types of commands that can be carried.
Command Execution |
After establishing a connection and specifying what command needs to be carried, you can execute it. To support this, the SqlCommand class is equipped with the ExecuteNonQuery() method. Its syntax is:
public override int ExecuteNonQuery();
This method does not take any argument. The SqlCommand object that calls it must have prepared a valid command. In future lessons, we will see that there are other ways a SqlCommand object can execute commands.
Well, the Command Timed Out |
In some cases, some actions take longer than others to execute. For this type of command, the compiler would keep trying to execute a command until successful. If there is a problem, this operation can take long or too long. You can specify how long the compiler should wait to try executing the command, again.
The SqlCommand.CommandTimeOut property allows you to specify the time to wait before trying to execute a command. The default value of this property is 30 (seconds). If you want a different value, assign it to your SqlCommand variable.
The Type of Command |
In this and the next few lessons, all of the commands we perform will be communicated as strings. When we study (stored) procedures, we will see other types of commands. To allow you to specify the type of command you want to perform, the SqlCommand class is equipped with the CommandType property, which is based on the CommandType enumeration.
The CommandType enumeration has three members: StoredProcedure, TableDirect, and Text. For a SqlCommand object, the default value is Text.
Reading Data |
Introduction |
A data command is used to initiate an action to perform on a database. To read data of a database, one of the objects you can use is called a data reader. To know how a data reader works, imagine you have a list of values as follows:
Genevieve |
Frank |
Paul |
Christine |
Germain |
If you use a data reader to read these values, the compiler visits the first value to read it. After reading it, the compiler moves to the second value. After visiting the second value, the compiler moves to the third value and so on. One of the particularities of a data reader is that, once it visits a value, reads it, and moves to the next value, the compiler cannot refer to the previous value. This can be illustrated as follows:
To support data readers, the .NET Framework provides, for a Microsoft SQL Server database, a class named SqlDataReader. To get a data reader, declare a variable of type SqlDataReader. This class does not have a constructor. This means that, to use it, you must (directly) specify where it would read its data from. To provide data to the reader, the SqlCommand class is equipped with the ExecuteReader() method that is overloaded with two versions. The simplest version of this method uses the following syntax:
public SqlDataReader ExecuteReader();
Based on this, before using a data reader, you should first create a command that would specify how data would be acquired. Once the data is read, you can pass it to the data reader by assigning the result of a call to a SqlCommand.ExecuteReader() method to a SqlDataReader object.
Using a SQL Data Reader
Once data is supplied to the reader, you can access it, one value at a time, from top to bottom. To access data that the reader acquired, you can call its Read() method whose syntax is:
public override bool Read();
As mentioned already, the Read() method simply reads a value and moves on. When reading the values, as mentioned already, the data reader reads one value at a time and moves to the next.