连接丢失后自动重新连接到MySql
我有一个使用 MySql 数据库的 c# 应用程序,问题是在一段时间不活动(8 小时)后或与数据库所在的服务器的连接丢失时,与数据库的连接将关闭并且无法执行数据库查询。我如何启用自动重新连接到数据库。
此致。
I have a c# application that uses a MySql database, the problem that after a period of inactivity (8 hours) or when connection to the server where database is host is lost, the connection to the database is closed and database queries cannot be executed. how can i enable the auto reconnect to the database.
Best regards.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为首先应该解决的问题是,为什么连接会连续开放 8 个小时?
我认为在大多数情况下,您将连接到数据库,执行您的操作,然后关闭它:
using 块将创建一个仅在该块内有效的连接。当块结束时,将在连接上调用 Dispose 方法并关闭并正确处置连接对象。这将防止您的应用程序在不需要时耗尽可用连接。
如果您需要确定连接是否打开,您的连接变量将具有一个
State
属性,该属性将是一个ConnectionState枚举。您可以使用以下内容进行检查:
希望有帮助。
I think the first thing that should be addressed is, why would a connection be open for 8 hours straight?
I'd think that in most cases you'll connect to the database, do your thing, and close it:
The using block will create a connection which is only valid within the block. When the block ends, the Dispose method will be called on the connection and close and properly dispose of the connection object. This will prevent your application from using up available connections when they aren't needed.
If you are in a situation where you'll need to determine if the connection is open, your connection variable will have a
State
property which will be a ConnectionState enumeration.You can check it using something like this:
Hope that helps.
在您的应用程序中,在进行任何查询之前,请测试您的连接是否仍处于活动状态。如果不是,则重新连接。等等瞧!
In your application, before any queries, test if your connection is still active. If it isn't, then reconnect it. Et voila !
如果尝试访问数据库失败,请再次运行连接命令。
Run your connection command again if the attempt to access the database fails.
您可以在连接字符串中使用选项
keepalive
和keepalivetimeout
。最好使用 MySqlConnectionStringBuilder 来实现这一点。You can use the option
keepalive
andkeepalivetimeout
in the connection string. It is best to use theMySqlConnectionStringBuilder
for that.感谢您的回答和建议。我有此要求是因为持久性被委托给非托管代码,并且在我的 C# 代码中我只调用此 API。
我通过更改
wait_timeout
MySQL 参数解决了我的问题,该参数将 28800 秒(8 小时)作为不活动时间的默认值。Thank you for your answers and suggestions. I have this requirement because persistence is delegated to unmanaged code and in my C# code I only make calls to this API.
I resolved my problem by changing the
wait_timeout
MySQL parameter that has 28800 seconds (8 hours) as the default value for the period of inactivity.