Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

c# - OleDbConnection.State issue with Microsoft Access

I have a C# application that reads/writes from/to an Access Database. I do this using an OleDbConnection.

Before a read / write, I want to check that my database connection is open. It should be straight-forward....

if (Connection.State != ConnectionState.Open) Connection.Open();

While this generally works well, it is not working for situations where network access is interrupted. The Connection.State is still recorded as 'Open', so I'd get an exception. So, I tried this:

Connection.ResetState();
if (Connection.ConnectionState(DatabaseType) != ConnectionState.Open) Connection.Open();

Nope... That's not working either, as the ResetState() method isn't actually resetting the state.

So I tried this extension method (a bit ugly...)

public static ConnectionState ConnectionState(this OleDbConnection connection, DatabaseType type)
{
    connection.ResetState();
    if (type == DatabaseType.Access)
    {
        //Reset state might not work... Check that the datasource is locatable
        if (!File.Exists(connection.DataSource)) return System.Data.ConnectionState.Closed;
        return connection.State;
    }
    return connection.State;
}

This "sort of" works, in that it correctly identifies that the DataSource can't be located. But then I get an exception when I try to open the database; not that it can't be found, but that its an invalid operation trying to open a connection that is already open!

I've spent about an hour trying to google to find a reliable way to get the true status of the database connection. Any other suggestions?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Correct way to use DbConnection is to create a new one for every command. Connection pooling means there is not usually a big overhead, and any network issues in between are sorted out automatically.

Make sure to Dispose correctly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...