利用 OdbcConnection,OdbcCommand,OdbcDataAdapter 的对象
连接数据库,执行select语句,语句如下:select * from XXX然后得到一个数据集,用如下的循环访问每一个DataRow:
try
{
foreach (DataRow cRow in cSectionsSet.Tables[0].Rows)
{
Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
}
}
catch (Exception cException)
{
string strMsg = cException.Message;
}结果时不时的(不是每一次都这样)在循环时发生异常,异常的消息是:
Collection was modified; enumeration operation might not execute.
为什么?如何解决?搞了2天没有解决。
连接数据库,执行select语句,语句如下:select * from XXX然后得到一个数据集,用如下的循环访问每一个DataRow:
try
{
foreach (DataRow cRow in cSectionsSet.Tables[0].Rows)
{
Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
}
}
catch (Exception cException)
{
string strMsg = cException.Message;
}结果时不时的(不是每一次都这样)在循环时发生异常,异常的消息是:
Collection was modified; enumeration operation might not execute.
为什么?如何解决?搞了2天没有解决。
解决方案 »
- C# Winform中有关TextBox邦定格式化为yyyy-MM-dd后,怎样清除TextBox中的内容
- 送分题
- word中的菜单栏是word主窗体的一个子窗体吗?
- c#读取xml的问题
- 安装部署的时候,我把一些 dll 文件放在 "System文件夹" ,安装完成后,一些机子可以用,一些机子却不能用,是什么原因?
- c# winform的listview图标与图标之间的间隔宽度该怎么调整?
- 运行时提示:找不到由程序集“”引用的文件“”
- 急问,怎么实现在同一个web网页上点击不同的视频号可以播放不同的视频阿?有大侠帮忙吗?谢谢阿!
- 急!!!一个bool型的函数为什么出错?
- 多线程数据错乱问题
- c#程序问题
- 汇编学的好的兄弟帮偶看道简单的题目
同一个数据表。
退一步讲,就算多线程访问并写了数据库,那又怎么了?难道数据库不支持多用户访问不是不能多线程访问数据库的问题,而是你在外边修改了记录集,因此用foreach会有问题,自己做循环处理。
即
changeforeach (DataRow cRow in cSectionsSet.Tables[0].Rows)
{
Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
}withfor( int i = 0; i < cSectionsSet.Tables[0].Rows.Count; i++ )
{
DataRow cRow = cSectionsSet.Tables[0].Rows[i];
Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
}
foreach (DataRow cRow in cSectionsSet.Tables[0].Rows)而改为for( int i = 0; i < cSectionsSet.Tables[0].Rows.Count; i++ )
能最大的避免错误。
To Knight94(愚翁)
thanks for your reply, you are a nice administrator.
But you said in your reply : program can avoid error as more as possible.
I think it means program can not resolve this problem completely, it's a regret.
actually i do not change anything in any thread else, i only read data after i
got it. maybe i made other mistake that i have not awared so far.so we can assume i modified data in other thread and go on this discussing, i
do not know if you have any better idea else ?to yiming0755()
Could you talk about it any more ?
for( int i = 0; i < cSectionsSet.Tables[0].Rows.Count; i++ )//There's safe
{
DataRow cRow = cSectionsSet.Tables[0].Rows[i];// But there is not safe, because other theads maybe modify row collection
Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
}So you should write code like this:
for( int i = 0; i < cSectionsSet.Tables[0].Rows.Count; i++ )
{
try
{
DataRow cRow = cSectionsSet.Tables[0].Rows[i];
Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
}
catch{ continue;}
}