SqlDataReader 是否具有与带有字符串键的 Get*(int index) 等效的功能?
我正在尝试使用 SqlDataReader (我非常清楚 Linq 等的优点,但我正在构建的应用程序部分是 Sql 生成器,因此 Linq 不符合我的需求)。不幸的是,我不确定使用 SqlDataReader 时的最佳实践是什么。我在代码中的几个地方使用了如下代码:
using (SqlDataReader reader = ...)
{
int ID = reader.GetInt32(0);
int tableID = reader.GetInt32(1);
string fieldName = reader[2] as string;
...//More, similar code
}
但感觉非常不稳定。如果数据库发生变化(在这种情况下实际上极不可能),代码就会中断。是否有与 SqlDataReader 的 GetInt32、GetString、GetDecimal 等效的函数,它采用列名而不是索引?在这种情况下,什么是最佳实践?什么最快?我的代码的这些部分是代码中最耗时的部分(我已经对其进行了几次分析),因此速度很重要。
[编辑]
我知道将索引器与字符串一起使用,我错误地表达了上面的内容。我遇到了运行缓慢的情况。我的代码工作正常,但我正在寻找任何可以在这些循环中偷回几秒钟的方法。通过字符串访问会减慢我的速度吗?我知道数据库访问是主要的时间密集型操作,对此我无能为力,因此我想减少每个访问元素的处理时间。
[编辑]
我决定只使用 GetOrdinal 运行,除非有人有更具体的例子。稍后我将进行效率测试。当我实际运行测试时,我会尽量记住发布它们。
I'm trying to use a SqlDataReader (I'm quite aware of the beauty of Linq, etc, but the application I'm building is partly a Sql Generator, so Linq doesn't fit my needs). Unfortunately, I'm not sure what the best practices are when using SqlDataReader. I use code like the following in several places in my code:
using (SqlDataReader reader = ...)
{
int ID = reader.GetInt32(0);
int tableID = reader.GetInt32(1);
string fieldName = reader[2] as string;
...//More, similar code
}
But it feels very unstable. If the database changes (which is actually extremely unlikely in this case) the code breaks. Is there an equivalent to SqlDataReader's GetInt32, GetString, GetDecimal, that takes a column name instead of an index? What's considered best practice in this case? What's fastest? These parts of my code are the most time intensive portions of my code (I've profiled it a few times) and so speed is important.
[EDIT]
I'm aware of using the indexer with a string, I misworded the above. I'm running into slow runtime. My code works fine, but I am looking for any way I can steal back a few seconds inside these loops. Would accessing by string slow me down? I know that the db-access is the primary time intensive operation, there's nothing I can do about that, so I want to cut back the processing time for each element accessed.
[EDIT]
I've decided to just run with GetOrdinal unless someone has more concrete examples. I'll run efficiency test later. I'll try to remember to post them when I actually run the tests.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
索引器属性采用字符串键,因此您可以执行以下操作。
其他建议
如果您担心字符串查找速度很慢,并且假设数字查找速度更快,您可以尝试使用
GetOrdinal
在循环遍历大数据之前查找列索引结果集。The indexer property takes a string key, so you can do the following.
Additional suggestion
If you're concerned about the string lookup being slow, and assuming numeric lookup is quicker, you could try using
GetOrdinal
to find the column indices before looping through a large result set.