建立了这个类以后,开始为CategoryList方法添加代码。
CategoryList方法获取数据的过程分为四步:1.通过SQLConnection和SQLDataSetCommand对象建立数据连接和命令对象。2.把命令对象类型设置为存储过程。3.把存储过程ListCategory的结果送入数据集。4.把包含结果的数据集返回给调用它的函数。
完整的CategoryList方法代码如下:
public DataSet CategoryList() {
// 建立数据连接和命令对象
SQLConnection myConnection = new SQLConnection
("server=localhost;uid=sa;pwd=;database=commercedotnet");
SQLDataSetCommand myCommand = new SQLDataSetCommand("ListCategory", myConnection);
// 设置命令对象类型为存储过程
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
// 建立和填充数据集
DataSet myDataSet = new DataSet();
myCommand.FillDataSet(myDataSet, "CategoryList");
// 返回数据集
return myDataSet;
}
// 建立数据连接和命令对象
SQLConnection myConnection = new SQLConnection
("server=localhost;uid=sa;pwd=;database=commercedotnet");
SQLDataSetCommand myCommand = new SQLDataSetCommand("ListCategory", myConnection);
// 设置命令对象类型为存储过程
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
// 建立和填充数据集
DataSet myDataSet = new DataSet();
myCommand.FillDataSet(myDataSet, "CategoryList");
// 返回数据集
return myDataSet;
}
ProductsList方法和CategoryList方法类似,但是ProductsList向存储过程传递了一个参数。
代码如下:
public DataSet ProductsList(int categoryID) {
// 建立数据连接和命令对象
SQLConnection myConnection = new SQLConnection
("server=localhost;uid=sa;pwd=;database=commercedotnet");
SQLDataSetCommand myCommand = new SQLDataSetCommand("ListProducts", myConnection);
// 设置命令对象类型为存储过程
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
// 向存储过程传递参数
SQLParameter parameterCategoryID = new SQLParameter("@CategoryID", SQLDataType.Int, 4);
parameterCategoryID.Value = categoryID;
myCommand.SelectCommand.Parameters.Add(parameterCategoryID);
// 建立和填充数据集
DataSet myDataSet = new DataSet();
myCommand.FillDataSet(myDataSet, "Products");
// 返回数据集
return myDataSet;
}
// 建立数据连接和命令对象
SQLConnection myConnection = new SQLConnection
("server=localhost;uid=sa;pwd=;database=commercedotnet");
SQLDataSetCommand myCommand = new SQLDataSetCommand("ListProducts", myConnection);
// 设置命令对象类型为存储过程
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
// 向存储过程传递参数
SQLParameter parameterCategoryID = new SQLParameter("@CategoryID", SQLDataType.Int, 4);
parameterCategoryID.Value = categoryID;
myCommand.SelectCommand.Parameters.Add(parameterCategoryID);
// 建立和填充数据集
DataSet myDataSet = new DataSet();
myCommand.FillDataSet(myDataSet, "Products");
// 返回数据集
return myDataSet;
}