——此文章摘自《C#高级编程(第
版)》定价
元 特价
元 购买
定义了数据连接后就可以从可用的列表中选择一个表(或视图)把该表从项目中拖放到活动的窗体上如图所示
图
在本例中选择Customers表把这个对象拖放到项目中时(可以把它拖放到窗体上或者拖放到服务器控件面板上)就会在窗体上添加一个派生于SqlDataAdapter或 OleDbDataAdaptor的对象(如果没有使用SQL Server)
生成的数据适配器包含SELECTINSERTUPDATE和DELETE命令显然也可以调用存储过程而不直接使用SQL命令向导生成的代码也可以完成这个工作Visual Studio NET给cs文件添加如下代码
private SystemDataSqlClientSqlCommand sqlSelectCommand;
private SystemDataSqlClientSqlCommand sqlInsertCommand;
private SystemDataSqlClientSqlCommand sqlUpdateCommand;
private SystemDataSqlClientSqlCommand sqlDeleteCommand;
private SystemDataSqlClientSqlDataAdapter sqlDataAdapter;
为每个SQL命令定义一个对象和一个SqlDataAdapter在文件后面的InitializeComponent方法中向导生成了创建这些命令和数据适配器的代码
在Visual Studio NET生成的代码中需要解释两个地方UpdateCommand和InsertCommand属性下面是显示有关信息的节选版本
//
// sqlInsertCommand
//
thissqlInsertCommandCommandText = @INSERT INTO Customers
(CustomerID CompanyName ContactName
ContactTitle Address City Region
PostalCode Country Phone Fax)
VALUES(@CustomerID @CompanyName @ContactName @ContactTitle
@Address @City @Region @PostalCode @Country @Phone @Fax);
SELECT CustomerID CompanyName ContactName ContactTitle Address
City Region PostalCode Country Phone Fax
FROM Customers WHERE (CustomerID = @CustomerID);
thissqlInsertCommandConnection = thissqlConnection;
thissqlInsertCommandParamatersAdd(
new SystemDataSqlClientSqlParamater(@CustomerID
SystemDataSqlDbTypeNVarChar CustomerID));
// Other Paramaters omitted for clarity
//
// sqlUpdateCommand
//
thissqlUpdateCommandCommandText = @UPDATE Customers
SET CustomerID = @CustomerID CompanyName = @CompanyName
ContactName = @ContactName ContactTitle = @ContactTitle
Address = @Address City = @City Region = @Region
PostalCode = @PostalCode Country = @Country
[] []