我只是检查了有关连接超时的堆栈溢出的其他帖子,但看起来每个人都使用
修复了它com.CommandTimeout = int.MaxValue;
和
dbaccess.ServerAddress = "Server=mysql;Database=MyDB;Connect Timeout=2147483;Uid=username;Pwd=mypassword";
不幸的是,40 秒后我仍然收到此错误消息:
The timeout period elapsed prior to completion of the operation or the server is not responding.
您可以看一下这两个屏幕截图。
MySQL Workbench 工作正常,执行相同的查询需要 48 秒。
我不能使用限制来减少获取的子集,因为我将信息集中在不同的表中。无法使用存储过程,因为信息也存储在不同的mysql服务器上。
非常感谢任何反馈。
费尔南多
编辑:
这是代码。我发布图像以显示执行时间,而不是错误消息。
public DataSet ExecuteQuery(string[] Query, TableMap[] TableMappings)
{
//Mysql vars
MySqlConnection con;
MySqlCommand com;
MySqlDataAdapter adapter;
DataSet ds;
con = new MySqlConnection();
con.ConnectionString = _serveraddress;
con.Open();
com = con.CreateCommand();
com.CommandType = System.Data.CommandType.Text;
foreach (string st in Query)
{
com.CommandText = com.CommandText + st;
}
com.CommandTimeout = int.MaxValue;
adapter = new MySqlDataAdapter(com.CommandText, con);
foreach (TableMap tm in TableMappings)
{
adapter.TableMappings.Add(tm.SourceTable, tm.TableSet);
}
ds = new DataSet();
adapter.Fill(ds);
return ds;
}
最佳答案
你的问题出在这一行
adapter = new MySqlDataAdapter(com.CommandText, con);
在这里您将命令文本传递给新的 MySqlDataAdapter。当然,这个 MySqlDataAdapter 不知道您在命令上设置的超时,因为两者(适配器和命令)没有链接在一起。
如果你改成
adapter = new MySqlDataAdapter(com);
然后您的适配器将使用 MySqlCommand 及其 CommandTimeout 属性
话虽如此,我真的建议您按照既定模式开始处理数据库代码
public DataSet ExecuteQuery(string[] Query, TableMap[] TableMappings)
{
// using statement will ensure proper closing and DISPOSING of the objects
using(MySqlConnection con = new MySqlConnection(_serveraddress))
using(MySqlCommand com = con.CreateCommand())
{
con.Open();
// Not needed, it is the default
// com.CommandType = System.Data.CommandType.Text;
foreach (string st in Query)
{
// Are you sure the st is properly terminated with a semicolon?
com.CommandText = com.CommandText + st;
}
com.CommandTimeout = int.MaxValue;
using(MySqlDataAdapter adapter = new MySqlDataAdapter(com))
{
foreach (TableMap tm in TableMappings)
adapter.TableMappings.Add(tm.SourceTable, tm.TableSet);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
}
}
using 语句在这里非常重要,特别是对于 MySql,它对未正确关闭的连接非常敏感,并且可能会停止您的程序并显示有关没有更多可用连接的错误消息。
关于c# - C# 上的 MySQL 连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40783150/