简体   繁体   English

MySql / Odbc连接问题

[英]MySql / Odbc connection problem

I'm accessing a MySql database via ODBC. 我正在通过ODBC访问MySql数据库。 It normally works fine, but if the database is stopped and restarted I have to restart my application in order to reconnect to the database. 它通常可以正常工作,但是如果数据库已停止并重新启动,则必须重新启动应用程序才能重新连接到数据库。

The code for accessing the database is like this: 访问数据库的代码如下:

        OdbcConnection connection = new OdbcConnection(connectString);
        OdbcCommand command = connection.CreateCommand();
        command.CommandType = CommandType.Text;
        command.CommandText = "select * from cds";
        OdbcDataAdapter dataAdapter = new OdbcDataAdapter(command);
        DataSet dataSet = new DataSet();
        connection.Open();
        dataAdapter.Fill(dataSet);
        connection.Close();

After a restart of the database, I get a 'MySql server has gone away' exception in dataAdapter.Fill method. 重新启动数据库后,我在dataAdapter.Fill方法中收到“ MySql服务器已消失”异常。 Is there any way I can reconnect to the database when I detect that the connection has broken? 当我检测到连接断开时,有什么方法可以重新连接到数据库?

I use VS2008 and MySql 5.1.30. 我使用VS2008和MySql 5.1.30。

This "restart the application in order to reconnect to the database" is simply a bad design decision. 这种“重新启动应用程序以重新连接到数据库”只是一个糟糕的设计决定。 The initialization of the database connection should not be put in the startup code, instead put it in a separate procedure, and in case one of your methods got the exception "MySql server has gone away" simply call this procedure in order to re-initialize the connection to the DB. 数据库连接的初始化不应该放在启动代码中,而应该放在一个单独的过程中,并且如果您的方法之一遇到异常“ MySql服务器已消失”,只需调用此过程即可重新初始化与数据库的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM