Page 87 - CSharp/C#
P. 87
Chapter 5: Accessing Databases
Examples
ADO.NET Connections
ADO.NET Connections are one of the simplest ways to connect to a database from a C#
application. They rely on the use of a provider and a connection string that points to your database
to perform queries against.
Common Data Provider Classes
Many of the following are classes that are commonly used to query databases and their related
namespaces :
• SqlConnection,SqlCommand,SqlDataReader from System.Data.SqlClient
• OleDbConnection,OleDbCommand,OleDbDataReader from System.Data.OleDb
• MySqlConnection, MySqlCommand, MySqlDbDataReader from MySql.Data
All of these are commonly used to access data through C# and will be commonly encountered
throughout building data-centric applications. Many other classes that are not mentioned that
implement the same FooConnection,FooCommand,FooDataReader classes can be expected to behave
the same way.
Common Access Pattern for ADO.NET Connections
A common pattern that can be used when accessing your data through an ADO.NET connection
might look as follows :
// This scopes the connection (your specific class may vary)
using(var connection = new SqlConnection("{your-connection-string}")
{
// Build your query
var query = "SELECT * FROM YourTable WHERE Property = @property");
// Scope your command to execute
using(var command = new SqlCommand(query, connection))
{
// Open your connection
connection.Open();
// Add your parameters here if necessary
// Execute your query as a reader (again scoped with a using statement)
using(var reader = command.ExecuteReader())
{
// Iterate through your results here
}
}
}
https://riptutorial.com/ 33

