SQL 超时异常

本文关键字:异常 超时 SQL | 更新日期: 2023-09-27 18:31:40

为什么我的代码中会出现此异常?我重新启动了服务器,更改了端口等,但没有任何效果。

怎么了?

DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("server=localhost;user=armin;password=root;");
con.Open();
SqlCommand result = new SqlCommand(
    "SELECT userid FROM KDDData.dbo.userprofile order by userid", con);
SqlDataReader reader = result.ExecuteReader();
dt.Load(reader);
List<string> userids = new List<string>(dt.Rows.Count);
foreach (DataRow item in dt.Rows)
{
    userids.Add(item.ItemArray[0].ToString().Trim());
}
con.Close();
con = new SqlConnection("server=localhost;user=armin;password=root;");
con.Open();
foreach (string user in userids)
{
    DataTable temp = new DataTable();
    SqlCommand result1 = new SqlCommand(
    "select itemid from KDDTrain.dbo.train where userid=" + user, con);
    SqlDataReader reader1 = result1.ExecuteReader();
    if (!reader1.HasRows)
    {
        continue;
    }
    temp.Load(reader1);
}

第一个查询工作正常,但第二个查询不能。如您所见,我什至使用其他一些SqlConnection但它仍然不起作用。

注意:我正在使用的数据库至少有 100 亿条记录,认为这可能是一个问题。

SQL 超时异常

连接字符串
中的某些内容看起来不正确我总是在MySql的连接字符串中看到"server=localhost; user=armin;password=root"而不是SqlServer,而是使用"Data Source=(LOCAL);Integrated Security=SSPI"或SqlServer的实例名称。您确定第一个查询有效吗?

但是我认为您应该使用适当的 using 语句

DataTable dt = new DataTable(); 
using(SqlConnection con = new SqlConnection("server=localhost;user=armin;password=root;"))
{
    using(SqlCommand result = new SqlCommand(
            "SELECT userid FROM KDDData.dbo.userprofile order by userid", con))
    {
        con.Open(); 
        using(SqlDataReader reader = result.ExecuteReader())
        {
           dt.Load(reader); 
           List<string> userids = new List<string>(dt.Rows.Count); 
           foreach (DataRow item in dt.Rows) 
           { 
              userids.Add(item.ItemArray[0].ToString().Trim()); 
           }
        } 
        DataTable temp = new DataTable(); 
        foreach (string user in userids) 
        { 
            using(SqlCommand result1 = new SqlCommand( 
            "select itemid from KDDTrain.dbo.train where userid=" + user, con))
            {
                using(SqlDataReader reader1 = result1.ExecuteReader())
                {
                    if (!reader1.HasRows)   continue; 
                    temp.Load(reader1); 
                }
            } 
        } 
   }

请插入此行

result1.CommandTimeout = 0;

对于第二个查询中的此行

SqlDataReader reader1 = result1.ExecuteReader();  

在以下之后处理您的读者:

foreach (DataRow item in dt.Rows)
{
    userids.Add(item.ItemArray[0].ToString().Trim()); 
} 

。并在温度后关闭连接。加载(读取器1)。 同时关闭读卡器1。

而不是这一切...干净的方法是使用 USING 初始化读卡器和连接。:)