菜鸟问题,数据库连接

lailong_74 2004-10-13 11:30:51
private void timerReceive_Tick(object sender, System.EventArgs e)
{
string mobile_no ;
string sp_id;
string msg;
string receive_time;
timerReceive.Enabled=false;
SqlCommand SqlcomReceiveBuff=new SqlCommand("select * from receivebuff",sqlConnPHS_SMS);
SqlDataReader DrReceiveBuff=SqlcomReceiveBuff.ExecuteReader();
while (DrReceiveBuff.Read())
{
mobile_no= DrReceiveBuff.GetValue(0).ToString();
sp_id= DrReceiveBuff.GetValue(1).ToString();
msg=DrReceiveBuff.GetValue(2).ToString();
receive_time=DrReceiveBuff.GetValue(3).ToString();
if (msg.ToUpper()=="LT")
{
SqlCommand SqlInsertUserChat=new SqlCommand("insert into chatuser (mobileno,ServeiceType,exitflag) values('" + mobile_no + "','01',0)",sqlConnPHS_SMS);

int re=SqlInsertUserChat.ExecuteNonQuery();
MessageBox.Show(re.ToString());
}
}
DrReceiveBuff.Close();
timerReceive.Enabled=true;
}
运行时提示“以有打开的与此连接相关的 DataReader,必须首先将它关闭”
修改SqlCommand SqlInsertUserChat=new SqlCommand("insert into chatuser (mobileno,ServeiceType,exitflag) values('" + mobile_no +"','01',0)",sqlCon);
用两个连接就能正常运行。
难道我必须的用两个连接吗?如果多表操作岂不是需要更多连接。
...全文
94 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
minrange 2004-10-13
  • 打赏
  • 举报
回复
DataReader是保持连接的,要么先关闭,要么用2个连接,要么不用DataReader
Andy__Huang 2004-10-13
  • 打赏
  • 举报
回复
參考﹕

private void button8_Click(object sender, System.EventArgs e)
{
string ss;
string conStr="server=ks052;uid=hdh;pwd=huang;database=hdh";

SqlConnection con=new SqlConnection();

try
{
con.ConnectionString=conStr;
con.Open();
SqlCommand com=new SqlCommand();
com.CommandText ="select * from tabx";
com.Connection=con;
SqlDataReader dr=com.ExecuteReader();

if(dr!=null && dr.HasRows)
{
while(dr.Read())
{
ss="";
//ss=dr["dept_no"].ToString() +"\t"+dr["person_no"].ToString() +"\t"+dr["sex"].ToString()+"\t"+dr["salary"].ToString() ;
ss=dr["dept_no"].ToString() + (char)9 +dr["person_no"].ToString() + (char)9 +dr["sex"].ToString()+ (char)9 +dr["salary"].ToString() ;

listBox1.Items.Add(ss);
}
}
}
catch(System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}
}
winnergx 2004-10-13
  • 打赏
  • 举报
回复
DataReader必须保持和数据库的连接是打开的。
yellowhwb 2004-10-13
  • 打赏
  • 举报
回复
用dataadapter将数据fill到dataset的table里,就行了。DataReader类似ADO里的RecordSet,效率比较高,但必须要保持连接,但dataset可以断开连接,一样使用!
wdtclv 2004-10-13
  • 打赏
  • 举报
回复
数据适配器dataadapter一样可以读数据阿
只不过效率不高
datareader是用来只读的并不能对数据进行修改
lailong_74 2004-10-13
  • 打赏
  • 举报
回复
不用DataReader那应该用什么读数据?谢谢。

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧