[英]Fill column in DataTable with output from SQL query
I have a DataTable with this structure: 我有一个具有以下结构的DataTable:
number amount destroyed together
1 19 3 22
2 20 3 23
3 11 0 11
The value in the destroyed
column is manually inserted by the user. 用户手动插入destroyed
列中的值。 However, I've created a table in SQL where a user can add a value for destroyed
and I want to take the value from this table. 但是,我已经在SQL中创建了一个表,用户可以在其中添加一个要destroyed
的值,我想从该表中获取该值。 I already have the proper SQL query for this. 我已经有合适的SQL查询了。
The following example will demonstrate. 以下示例将进行演示。
Here is output from the query : 这是查询的输出:
number destroyed type
1 3 papper
2 1 papper
According to the structure of the DataTable it should insert a value for destroyed
from this SQL query into DataTable when 根据DataTable的结构,在以下情况下,应将此SQL查询中要destroyed
的值插入DataTable中
Query.number = DataTable.Number
So according to this example it should look like: 因此,根据此示例,它应类似于:
number amount destroyed together
1 19 3 22
2 20 1 21
3 11 0 11
How do I accomplish this? 我该如何完成?
You haven't posted how you're connecting and executing your SQL statement. 您尚未发布如何连接和执行SQL语句。 Using SqlConnection
and friends to execute a statement: 使用SqlConnection
和好友执行一条语句:
// For each row in the DataTable...
for (int i = 0; i < dataTable.Rows.Count; i++) {
// Get record where number equals the DataTable's "number" column for this row
// Then select the destroyed value:
string sql = String.Format("SELECT * FROM Table WHERE number='{0}' THEN destroyed", dataTable.Rows[i]["number"].ToString());
int destroyedCount = 0;
// Execute the SQL query, return value to `destroyedCount`
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql);
try
{
conn.Open();
destroyedCount = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// Set the table value to the SQL command's returned value
dataTable.Rows[i]["destroyed"] = destroyedCount;
// Assuming you want amount + destroyed = together
int amountCount = 0;
// Parse the table's current value for `amount`
try
{
amountCount = (int)dataTable.Rows[i]["amount"];
}
catch (ArgumentNullException argEx)
{
// Handle exception
}
catch (FormatException formatEx)
{
// Handle exception
}
// Set the `together` column to `amount` + `destroyed`
dataTable.Rows[i]["together"] = (amountCount + destroyedCount).ToString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.