我尝试将datagridview数据发送到sql server。我有逻辑层和数据层
// calling logic layer
RecLogic.ProcessRecoveryData(dataGridView1.DataSource)
然后我从datalayer
访问该数据源//this is my logic class
public void ProcessRecoveryData(object dataSource)
{
try
{
new RecoveryData().ProcessRecoveryData(dataSource);
}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
我从逻辑层
访问该数据源//this is my data class
public void ProcessRecoveryData(object dataSource)
{
try
{
sqlCon.Open();
sqlCmd.Connection = sqlCon;
SqlDataAdapter sqlAdp = new SqlDataAdapter();
for (int i = 0; i < dataGridView1.dataSource.Rows.Count; i++)
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "my_sp"; sqlCmd.Parameters.AddWithValue("@p1",dataGridView1.dataSource.Rows[i].Cells["text"].Value); sqlCmd.Parameters.AddWithValue("@p2",dataGridView1.dataSource.Rows[i].Cells["text"].Value);
sqlAdp.SelectCommand = sqlCmd;
}
}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
sqlCmd.Dispose();
}
}
如何将数据层中的数据源发送到sql?
答案 0 :(得分:0)
您需要定义一个Table类型,并在您的存储过程中具有该类型的参数...... 例如 在SQL ....
CREATE TYPE myTableType AS table (
categoryBridgeId uniqueIdentifier,
denomination int,
qty int
);
CREATE PROCEDURE [dbo].[My_Sproc] (@items myTableType READONLY,
etc
然后在C#中,您可以将DataTable传递给storred过程...
..
var tblParam = new SqlParameter("@items", SqlDbType.Structured);
tblParam.Value = GetItemsAsDataTable(req);
tblParam.TypeName = "dbo.myTableType ";
cmd.Parameters.Add(tblParam);
...
private static DataTable GetItemsAsDataTable(ECodeAddItemsToBasketRequest req)
{
var result = new DataTable();
result.Columns.Add("categoryBridgeId", typeof(Guid));
result.Columns.Add("denomination", typeof(int));
result.Columns.Add("qty", typeof(int));
foreach (var item in req.ps)
{
Guid category = item.cid;
int denomination = item.d;
int qty = item.q;
result.Rows.Add(category, denomination, qty);
}
return result;
}
希望这会有所帮助 - 祝你好运!