Tài liệu Mapping Tables and Columns - Pdf 87


Mapping Tables and Columns
In Chapter 3
, "Introduction to Structured Query Language (SQL)," you learned that the
AS keyword is used to specify an alias for a table or column. The following example uses
the AS keyword to alias the CustomerID column as MyCustomer and also alias the
Customers table as Cust:
SELECT CustomerID AS MyCustomer, CompanyName, Address
FROM Customers AS Cust
WHERE CustomerID = 'ALFKI';
Figure 10.2
shows the results of this SELECT statement.

Figure 10.2: Using the AS keyword
The following code uses this SELECT statement to populate a DataSet object named
myDataSet:
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT CustomerID AS MyCustomer, CompanyName, Address " +
"FROM Customers AS Cust " +
"WHERE CustomerID = 'ALFKI'";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet, "Customers");
mySqlConnection.Close();
Notice the Fill() method specifies the name of the DataTable as Customers, which is
known as the source DataTable name.
To map a DataTable in your DataSet, you create an object of the DataTableMapping
class using the Add() method; this class belongs to the System.Data.Common namespace,

class. This object is a collection of DataColumnMapping objects. You use a
DataColumnMapping object to map a column name from the database to a different
DataColumn name, therefore, the previous example maps the CustomerID column name
from the database to the DataColumn name MyCustomer.
Listing 10.13
illustrates how to map table and column names using the code shown in this
section.
Listing 10.13: MAPPINGS.CS

/*
Mappings.cs illustrates how to map table and column names
*/

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;

class Mappings
{
public static void Main()
{
SqlConnection mySqlConnection =
new SqlConnection(
"server=localhost;database=Northwind;uid=sa;pwd=sa"
);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT CustomerID AS MyCustomer, CompanyName, Address " +
"FROM Customers AS Cust " +

}
}
}

The output from this program is as follows:
myDataTableMapping.DataSetTable = Cust
myDataTableMapping.SourceTable = Customers
CustomerID = ALFKI
CompanyName = Alfreds Futterkiste
Address = Obere Str. 57


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status