c# - 使用 SQL 时 DBConnection 超时

标签 c# sql database timeout

我正在使用 C# 创建简单的应用程序,该应用程序将在 1 分钟后重复检查数据库。我正在使用线程来使其更有礼貌并减少资源。这些线程将同步地一次只执行一个函数。

我的问题是

Exception was unhandled : DBConnection
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

我了解我与数据库的连接超过了时间限制。那么,如何解决这个问题呢?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GDEX.Master;
using GDEX.DataAccess;
using System.Globalization;
using System.IO;
using System.Threading;

namespace SMPPTransfer
{
    public partial class frmDBTS : Form
    {
        string updateProbRecord = string.Empty;
        string selectProbRecord = string.Empty;
        string selectProbStat = string.Empty;
        string updateStat = string.Empty;
        string selectAssignTo = string.Empty;
        string CheckPODStatus = string.Empty;

        DataTable dtStat = null;
        DataTable dtPOD = null;
        DataTable dtAssignNo = null;

        bool stopThreads = false;
        AutoResetEvent blockThread1 = new AutoResetEvent(true);
        AutoResetEvent blockThread2 = new AutoResetEvent(false);

        delegate void SetTextCallback(string text);
        GDexSqlSvConnection dbCon;

        public frmDBTS()
        {
            InitializeComponent();
            String connSQLSvr = "Data Source=<my IP>;Initial Catalog=<database>;User ID=<username>;Password=<pwd>;";
            dbCon = new GDexSqlSvConnection(connSQLSvr);

            Thread thread1 = new Thread(new ThreadStart(UpdateProbRec));
            Thread thread2 = new Thread(new ThreadStart(UpdateProbStat));

            thread1.Start();
            thread2.Start();
        }

        private void UpdateProbRec()
        {
            while (stopThreads == false)
            {
                blockThread1.WaitOne();

                SetText1("Entered Thread 1");
                SetText2("Out Thread 2");                

                //Get POD status
                CheckPODStatus = "select top 100 * from (select cn"
                                 + " FROM gdexpdb.dbo.prob_record where solve = 'N' and status!='S') A "
                                 + " join (select cn, cn_date"
                                 + " from gdexpdb.dbo.pod_data where type='rts' or type = 'pod' or type = 'm_pod' or type = 'm_rts') B "
                                 + "on A.CN=B.cn";

                dtPOD = dbCon.ExecuteQueryAndGetDataTable(CheckPODStatus); //Problem occur from here and only for this function only

                DateTime cnDate;
                string cnDateCon;
                for (int iii = 0; iii < dtPOD.Rows.Count; iii++)
                {
                    cnDate = (DateTime)dtPOD.Rows[iii][2];

                    cnDateCon = cnDate.ToString("yyyy-MM-dd");

                    updateProbRecord = "update gdexpdb.dbo.prob_record set solve='Y', solve_date='" + cnDateCon + "', status='S' "
                                        + "where cn='" + dtPOD.Rows[iii][0] + "'";
                    dbCon.ExecuteNonQuery(updateProbRecord);
                }

                dtPOD.Clear();
                Thread.Sleep(30000);
                blockThread2.Set();
            }
        }

        private void UpdateProbStat()
        {
            while (stopThreads == false)
            {
                blockThread1.WaitOne();

                SetText2("Entered Thread 2");
                SetText1("Out Thread 1");

                selectProbStat = "select username from gdexpdb.dbo.prob_stat";

                dtStat = dbCon.ExecuteQueryAndGetDataTable(selectProbStat);
                int[] userNo = new int[dtStat.Rows.Count];

                for (int x = 0; x < dtStat.Rows.Count; x++)
                {
                    selectAssignTo = "select count(*) as assignNo from gdexpdb.dbo.prob_record where assign_to='" + dtStat.Rows[x][0]+ "'";
                    dtAssignNo = dbCon.ExecuteQueryAndGetDataTable(selectAssignTo);

                    updateStat = "update gdexpdb.dbo.prob_stat set stat=" + dtAssignNo.Rows[0][0] + "where username='" + dtStat.Rows[x][0] + "'";
                    dbCon.ExecuteNonQuery(updateStat);
                }

                dtStat.Clear();
                dtAssignNo.Clear();
                Thread.Sleep(100000);
                blockThread1.Set();
            }
        }

        private void SetText1(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.TextThread1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText1);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.TextThread1.Text = text;
            }
        }

        private void SetText2(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.TextThread2.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText2);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.TextThread2.Text = text;
            }
        }
    }
}

最佳答案

GDexSqlSvConnection 类中 - 函数 ExecuteQueryAndGetDataTableExecuteNonQuery 和其他...将 CommandTimeout 属性设置为数据库命令您用于查询数据库的实例。

例如:

MyCommand.CommandTimeout = 120; // 2 Minutes Timeout

关于c# - 使用 SQL 时 DBConnection 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11134365/

相关文章:

c# - C# 中的结构指针初始化

c# - 减少向三个表发送信息所需的 SqlCommand 数量

部分列的 SQL 搜索

mysql - 如何选择一列日期并使用它来驱动第二个 SELECT 语句?

c# - XNA 在全屏->窗口转换中丢失标题栏主题

c# - 为什么跨线程以这种方式工作?

java - preparedstatement 关闭后有没有办法获取结果集? ( java )

ruby-on-rails - 在 Rails 中实现租赁商店 : how to track an inventory state over time?

java - 如何监听 Firebase setValue 完成

java - 对于 Oracle,connection.getCatalog() 返回 null