怎样判断有没有打开和数据库的连接

gxz01 2003-07-25 05:52:32
我相判断有没有打开这个连接,如果没有找到这个文件就返回,但
下面的代码好向不管用.

string strConn="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=f:\\pcadex.v31\\adreport\\zxg\\hk\\SectionCode.mdb";
SectionCodeConnection=new OleDbConnection(strConn);
if(SectionCodeConnection==null)
{
MessageBox.Show("打开文件错误.");
return;
}

SectionCodeConnection.Open();
...全文
112 5 打赏 收藏 举报
写回复
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
dahuzizyd 2003-07-26
  • 打赏
  • 举报
回复
来分析你的代码
SectionCodeConnection=new OleDbConnection(strConn);后你的SectionCodeConnection实例就已经存在了,
if(SectionCodeConnection==null)//判断SectionCodeConnection是否存在,而不是数据库是否打开了
{
MessageBox.Show("打开文件错误.");
return;
}
中的条件是不可能满足的,也就不会出现你的错误提示,数据库打开是在这里进行的:
SectionCodeConnection.Open();所以判断数据库是否打开应该在这里,你可以这样:
try
{
SectionCodeConnection.Open();
}
finally
{
if(SectionCodeConnection.State == ConnectionState.Open)
{
//数据库已连接上
}
else
{
//数据库未连接上
}
}

teenty 2003-07-25
  • 打赏
  • 举报
回复
你可以先判断此文件是否存在呀
smartcreater 2003-07-25
  • 打赏
  • 举报
回复
表示数据库连接状态:SqlConnection.state
gxz01 2003-07-25
  • 打赏
  • 举报
回复
不管用,如果我把数据库名字换掉,不会出现 ("打开文件错误.");
这句我写的提示.
panyee 2003-07-25
  • 打赏
  • 举报
回复
if(SectionCodeConnection.State == ConnectionState.Open)
{
//已经打开
}
else
{
//没打开
}
相关推荐
发帖
C#

10.9w+

社区成员

.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
帖子事件
创建了帖子
2003-07-25 05:52
社区公告

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