日期:2014-05-17  浏览次数:20984 次

请问,SqlParameter.SourceColumn属性,简直不懂
SqlParameter.SourceColumn 属性:http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlparameter.sourcecolumn.aspx
获取或设置源列的名称,该源列映射到 DataSet 并用于加载或返回 Value

请帮忙理解一下这个属性,MSDN都看不懂,百度搜索也没有
谢谢!!

------解决方案--------------------
跟强类型DataSet配合使用比较好

比如你数据库的列是 kk,强类型dataset 有一列属性是 KK,
你要update的时候,假设有语句 kk=@kk
parameter["@kk"]=MyDataset.KK;

这样当你update 的时候,kk跟KK就对应起来了
------解决方案--------------------
看一下这个例子。
public static SqlDataAdapter CreateSqlDataAdapter(SqlConnection connection)
{
SqlDataAdapter adapter = new SqlDataAdapter();

// Create the commands.
adapter.InsertCommand = new SqlCommand(
"INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES (@CustomerID, @CompanyName)", connection);

// Create the parameters.
adapter.InsertCommand.Parameters.Add("@CustomerID", 
SqlDbType.Char, 5, "CustomerID");
adapter.InsertCommand.Parameters.Add("@CompanyName", 
SqlDbType.VarChar, 40, "CompanyName");

return adapter;
}
其中,adapter.InsertCommand.Parameters.Add("@CustomerID", 
SqlDbType.Char, 5, "CustomerID");
上面这行代码的意思是:在上面的INSERT语句中,参数"@CustomerID"的数据库类型为Char[5],这个参数的值是传给表中"CustomerID"这个字段的。"CustomerID"这个就是SqlParameter.SourceColumn的值。在这里,SqlParameter.SourceColumn对应的就是接收参数的数据表的列。

再看下面这个例子
private static void AdapterUpdate(string connectionString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT CategoryID, CategoryName FROM Categories",
connection);

//定义UpdateCommand的语句,在这个语句中,包含了两个参数@CategoryName和@CategoryID,第一个是INPUT参数、第二个既是INPUT参数,又是OUTPUT参数//
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = @CategoryName " +
"WHERE CategoryID = @CategoryID", connection);

//添加一个sqlParameter,将参数"@CategoryName"与列名"CategoryName"对应起来//
dataAdpater.UpdateCommand.Parameters.Add(
"@CategoryName", SqlDbType.NVarChar, 15, "CategoryName");

//添加一个sqlParameter,将参数"@CategoryID"与列名"CategoryID"对应起来//
SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(
"@CategoryID", SqlDbType.Int);
parameter.SourceColumn = "CategoryID";
parameter.SourceVersion = DataRowVersion.Original;

DataTable categoryTable = new DataTable();
dataAdpater.Fill(categoryTable);

//修改DataTable中的值//
DataRow categoryRow = categoryTable.Rows[0];
categoryRow["CategoryName"] = "New Beverages";

//用DataTable中修改后的值更新数据库中的值,与上面的结合,就是从DataTable中获取参数@CategoryName=列"CategoryName"的值即"New Beverages";从DataTable中获取参数@CategoryID=更新记录更新前的列"CategoryID"的值,假设为1。然后再在数据库Categories表的列"CategoryID"中查找值为@CategoryID的记录,进行更新。//
dataAdpater.Update(categoryTable);

Console.WriteLine("Rows after update.");
foreach (DataRow row in categoryTable.Rows)
{
{
Console.WriteLine("{0}: {1}", row[0], row[1]);
}
}
}
}

也就是说,SqlParameter.SourceColumn这个属性就是和参数对应的数据表中的列名。具体是将参数的值传入到这个列中,还是从这个列中检索查找与这个参数值相同的记录。需要看具体的sql语句和参数的INPUT、OUTPUT等传输类型。反正就是参数和具体列的一个对应关系。
说了这么多,也不知道你明没明白。
上面两个例子是从msdn上摘的,你可以参考一下。
http