This article has been excerpted from book "A Programmer's Guide to ADO.NET in C#".
Similar to the OldDbCommand object, you create Sql and ODBC Command objects by using SqlCommand and OdbcCommand classes. You can pass the same arguments as discussed previously. The only difference is the connection string. For Example, listing 5-31 uses SqlCommand and SqlConnection to connect to SQL server database. As you can see from listing 5-31, the only changes are the class prefixes and the connection string. Similarly, you can use the OdbcCommand object.
Listing 5-31. Using SqlCommand to access a SQL Server database
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Connection and SQL strings
string SQL = "SELECT * FROM Orders";
// create a connection object
string ConnectionString = "Integrated security =SSPI;" + "Initial Catalog = Northwind;" + "Data Source = MAIN-SERVER; ";
SqlConnection conn = new SqlConnection(ConnectionString);
// create command object
SqlCommand cmd = new SqlCommand(SQL, conn);
// open connection
conn.Open();
// call command's ExcuteReader
SqlDataReader reader = cmd.ExecuteReader();
try
{
while (reader.Read())
{
Console.Write("OrderID:" + reader.GetInt32(0).ToString());
Console.Write(" ,");
Console.WriteLine("Customer : " + reader.GetString(1).ToString());
}
}
finally
{
// close reader and connection
reader.Close();
conn.Close();
}
}
}
}
The output of Listing 5-31 looks Figure 5-31.
Figure 5-31. Output of listing 5-31
Conclusion
Hope this article would have helped you in understanding Creating Sql and ODBC Command Objects in ADO.NET. See my other articles on the website on ADO.NET.
|
This essential guide to Microsoft's ADO.NET overviews C#, then leads you toward deeper understanding of ADO.NET. |