DataTable 查找或如果未找到则插入行
我有一个包含 2 列的 DataTable dt。第一个列(称为 CustomerId)是唯一的并且不允许为空。第二个允许空值并且不唯一。
我从一个方法中获取一个 CustomerId,然后如果该 CustomerId 不存在,则插入一条新记录;如果该 CustomerId 存在,则将与该 CustomerId 相对应的第二列中的内容加 1。
我不知道我应该如何处理这个问题。我编写了一个 select 语句(返回 System.Data.DataRow),但我不知道如何测试它是否返回空字符串。
目前我有:
//I want to insert a new row
if (dt.Select("CustomerId ='" + customerId + "'") == null) //Always true :|
{
DataRow dr = dt.NewRow();
dr["CustomerId"] = customerId;
}
I have a DataTable dt with 2 columns. First col (call it CustomerId) is unique and doesn't allow nulls. the second one allows nulls and is not unique.
From a method I get a CustomerId and then I would like to either insert a new record if this CustomerId doesn't exist or increment by 1 what's in the second column corresponding to that CustomerId if it exists.
I'm not sure how I should approach this. I wrote a select statement (which returns System.Data.DataRow) but I don't know how to test whether it returned an empty string.
Currently I have:
//I want to insert a new row
if (dt.Select("CustomerId ='" + customerId + "'") == null) //Always true :|
{
DataRow dr = dt.NewRow();
dr["CustomerId"] = customerId;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果数据表正在由数据库填充。我建议将 customerid 设置为身份列。这样,当您添加新行时,它将自动创建一个新的 customerid,该新的 customerid 是唯一的,并且比之前的 id 大 1(取决于您如何设置身份列),
我将检查从 select 语句返回的行数。就像
我也会使用 string.Format...
所以它看起来像这样
If the datatable is being populated by a database. I would recommend making the customerid a identity column. That way when you add a new row it will automatically create a new customerid which will be unique and 1 greater than the previous id (depending on how you setup your identity column)
I would check the row count which is returned from the select statement. Something like
I would also use string.Format...
So it would look like this
这是我解决类似问题的方法。您可以修改它以满足您的需要。
This is my method to solve similar problem. You can modify it to fit your needs.
Select
方法返回 DataRow 对象的数组。只需检查它的长度是否为零(它永远不会null
)。顺便说一下,不要像本示例那样直接在代码中编写此类语句。有一种破坏代码安全性的技术称为“SQL 注入”,我鼓励您阅读维基百科文章。简而言之,如果您将用户的
customerId
作为字符串获取,经验丰富的用户可能会编写由您的数据库执行的 SQL 脚本,并且可能会做出有害的事情。我没有数据库编程经验,这只是“常识”......The
Select
Method returns an array of DataRow objects. Just check if its length is zero (it's nevernull
).By the way, don't write such statements in the code directly as in this example. There's a technique for breaching your code's security called "SQL Injection", I encourage you to read the Wikipedia Article. In brief, an experienced user could write SQL script that gets executed by your database and potentially do harmful things if you're taking
customerId
from the user as a string. I'm not experienced in database programming, this is just "general knowledge"...