c# - 处理同时连接两次数据库
问题描述
我正在使用一个计时器,它每 1ms 导致一次与数据库的连接,当有时它在前一个连接关闭之前连接到数据库时,这会导致问题。
有没有办法处理这个问题?
` protected void timerTest_tick(object sen, EventArgs e)
{
string sql = "SELECT * FROM [TableActions] WHERE ID =" + Session["LobbyID"];
Connection cn = new Connection();
OleDbDataReader reader = cn.GetReader(sql);
if (reader.Read())
{
Session["GNACode"] = reader.GetString(2);
}
cn.closecon();
}`
解决方案
你应该转移Connection cn = new Connection();
到班级范围
并移动cn.closecon();
以形成关闭事件。
public class YourForm{
private static Connection cn = null;
YourForm(){
if (cn == null)
{
instance = new Connection();
}
}
protected void timerTest_tick(object sen, EventArgs e)
{
string sql = "SELECT * FROM [TableActions] WHERE ID =" + Session["LobbyID"];
OleDbDataReader reader = cn.GetReader(sql);
if (reader.Read())
{
Session["GNACode"] = reader.GetString(2);
}
}
private void CloseEvent(){
cn.closecon();
}
}
推荐阅读
- stm32 - 如何禁用 stm32f405 jtag 接口
- react-native - React Native 中的对象内的对象
- c++ - Qt 错误:QSqlQuery::value: 在尝试从表中检索统计信息时未定位在有效记录上 (QComboBox)
- c# - 如何在 WinForms 图表中创建从 (0,0) 到 (0,n) 的线?
- r - 交互式地图似乎没有正确过滤数据(闪亮,传单)
- javascript - 将选择列表中的所有项目获取到控制器
- ruby-on-rails - 尝试使用 ruby on rails 运行应用程序时出现控制器错误
- postgresql - 在 Postgres UPDATE 查询中循环 - 第 2 部分
- ajax - 如何在laravel中单击时从ajax重定向到视图?
- pyspark - 更新 pyspark 中的现有列而不更改旧值