SQL 服务停止后 Conn.Open() 仍然有效

发布于 2024-10-02 19:39:27 字数 5737 浏览 5 评论 0原文

我遇到了 sql server 2005 SP2 的问题,我创建了一个 Windows 窗体,上面有一个按钮,并执行以下步骤:

  1. 确保 Sql 服务正在运行,然后单击按钮,一切正常
  2. 停止 Sql 服务,然后再次点击按钮,在我的机器上,LINE 1代码处没有异常,在LINE 2处发生异常,这是异常信息:

Message :向服务器发送请求时发生传输级错误。 (提供程序:共享内存提供程序,错误:0 - 管道的另一端没有进程。)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ReconnectSQL
{
    public partial class Form1 : Form
    {

        private string m_ConnectionString = @"Server=(local); Database=testDB; User ID=sa; Password=admins; Connection Timeout=15";

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        public DataTable GetByFillDataTable()
        {
            try
            {
                SqlCommand cmd = new SqlCommand("getalldata");
                cmd.CommandType = CommandType.StoredProcedure;

                DataTable dt = this.GetDataTable(cmd);
                return dt;
            }
            catch
            {
                throw;
            }
        }


        #region common funcs
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        private DataTable GetDataTable(SqlCommand cmd)
        {
            DataTable dt = new DataTable();

            using (SqlConnection conn = new SqlConnection(this.m_ConnectionString))
            {
                try
                {
                    conn.Open();  // LINE 1
                }
                catch (Exception eX)
                {
                    throw;
                }

                using (SqlDataAdapter adapter = new SqlDataAdapter())
                {
                    try
                    {
                        cmd.Connection = conn;
                        cmd.CommandTimeout = conn.ConnectionTimeout;
                        adapter.SelectCommand = cmd;
                        adapter.Fill(dt);  // LINE 2
                    }
                    catch (Exception eX)
                    {
                        throw;
                    }
                }
            }

            return dt;
        }

        #endregion       

        private void button2_Click(object sender, EventArgs e)
        {

            try
            {
                DataTable dt = GetByFillDataTable();
                listBox1.Items.Add("GetByFillDataTable is called without exceptions!");
            }
            catch (Exception ex)
            {
                listBox1.Items.Add(ex.Message);
            }            }
    }
}

详细的异常信息:

-       [System.Data.SqlClient.SqlException]    {"A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)"} System.Data.SqlClient.SqlException
+       base    {"A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)"} System.Data.Common.DbException {System.Data.SqlClient.SqlException}
        Class   20  byte
+       Errors  {System.Data.SqlClient.SqlErrorCollection}  System.Data.SqlClient.SqlErrorCollection
        LineNumber  0   int
        Number  233 int
        Procedure   null    string
        Server  "(local)"   string
        Source  ".Net SqlClient Data Provider"  string
        State   0   byte

StackTrace

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParserStateObject.WriteSni()
   at System.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode)
   at System.Data.SqlClient.TdsParserStateObject.ExecuteFlush()
   at System.Data.SqlClient.TdsParser.TdsExecuteRPC(_SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
   at ReconnectSQL.Form1.GetDataTable(SqlCommand cmd) in E:\_public_\sqlFail\ReconnectSQL\ReconnectSQL\Form1.cs:line 138

I have met a issue with sql server 2005 SP2, I have created a windows form and with a button on it, and with the following steps:

  1. Make sure Sql service is running, then click the button, everything is OK
  2. Stop the Sql service, and then click the button again, on my machine, there is not exception at the code of LINE 1, exception occurred at LINE 2, and this is the exception info:

Message: A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ReconnectSQL
{
    public partial class Form1 : Form
    {

        private string m_ConnectionString = @"Server=(local); Database=testDB; User ID=sa; Password=admins; Connection Timeout=15";

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        public DataTable GetByFillDataTable()
        {
            try
            {
                SqlCommand cmd = new SqlCommand("getalldata");
                cmd.CommandType = CommandType.StoredProcedure;

                DataTable dt = this.GetDataTable(cmd);
                return dt;
            }
            catch
            {
                throw;
            }
        }


        #region common funcs
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        private DataTable GetDataTable(SqlCommand cmd)
        {
            DataTable dt = new DataTable();

            using (SqlConnection conn = new SqlConnection(this.m_ConnectionString))
            {
                try
                {
                    conn.Open();  // LINE 1
                }
                catch (Exception eX)
                {
                    throw;
                }

                using (SqlDataAdapter adapter = new SqlDataAdapter())
                {
                    try
                    {
                        cmd.Connection = conn;
                        cmd.CommandTimeout = conn.ConnectionTimeout;
                        adapter.SelectCommand = cmd;
                        adapter.Fill(dt);  // LINE 2
                    }
                    catch (Exception eX)
                    {
                        throw;
                    }
                }
            }

            return dt;
        }

        #endregion       

        private void button2_Click(object sender, EventArgs e)
        {

            try
            {
                DataTable dt = GetByFillDataTable();
                listBox1.Items.Add("GetByFillDataTable is called without exceptions!");
            }
            catch (Exception ex)
            {
                listBox1.Items.Add(ex.Message);
            }            }
    }
}

Detailed exception info:

-       [System.Data.SqlClient.SqlException]    {"A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)"} System.Data.SqlClient.SqlException
+       base    {"A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)"} System.Data.Common.DbException {System.Data.SqlClient.SqlException}
        Class   20  byte
+       Errors  {System.Data.SqlClient.SqlErrorCollection}  System.Data.SqlClient.SqlErrorCollection
        LineNumber  0   int
        Number  233 int
        Procedure   null    string
        Server  "(local)"   string
        Source  ".Net SqlClient Data Provider"  string
        State   0   byte

StackTrace

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParserStateObject.WriteSni()
   at System.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode)
   at System.Data.SqlClient.TdsParserStateObject.ExecuteFlush()
   at System.Data.SqlClient.TdsParser.TdsExecuteRPC(_SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
   at ReconnectSQL.Form1.GetDataTable(SqlCommand cmd) in E:\_public_\sqlFail\ReconnectSQL\ReconnectSQL\Form1.cs:line 138

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情话已封尘 2024-10-09 19:39:27

经过一番调查,即使sql停止,连接似乎仍然存在于连接池中,因此在sql启动后,通过调用 conn.Open() 它从池中获取应该无效的连接对象,然后 SqlDataAdapter.Fill导致异常

http:// Social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/99963999-a59b-4614-a1b9-869c6dff921e

After some investigations, it seems the connection still exist in the connection pool even sql is stopped, so after sql is started and by calling conn.Open() it get the connection object from the pool which should be invalid, then the SqlDataAdapter.Fill cause the exception

http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/99963999-a59b-4614-a1b9-869c6dff921e

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文