微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#控制台应用程序无效的操作异常

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.sql;
using System.Data.sqlClient;

namespace BissUpdater
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "Data Source=H....; 
                Initial Catalog=LANDesk; Persist Security Info=True; 
                User ID=Mainstc; Password=xxxxxxxx";

            sqlConnection con = new sqlConnection(connectionString);
            con.open();
        }
    }
}

sql Connection引发了无效的操作异常.

“Invalid Operation. The connection is closed”.

这是我的完整代码.在另一个程序中,它完美无缺.

这是第二次,这不起作用.我正在使用VS2005 …也许我的程序已损坏?

堆栈跟踪:

at System.Data.sqlClient.sqlConnection.GetopenConnection()
at
System.Data.sqlClient.sqlConnection.get_ServerVersion()

解决方法

这样做的正确方法应该是这样的:
static void Main(string[] args) {
    string connectionString = "Data Source=H....; 
    Initial Catalog=LANDesk;User ID=Mainstc; Password=xxxxxxxx"; 
    // removed Persist Security Info=True; 


    using(sqlConnection con = new sqlConnection(connectionString))
    {
      if (con.State==ConnectionState.Closed)
      {                      
          con.open();   
      }
    }


}

使用Using语句,它将自动处理您的sql连接.

检查这个:Best Practices for Using ADO.NET on MSDN

其他事项:使用sql Management Studio并尝试使用连接字符串中的sql身份验证登录凭据,如果使用该帐户成功连接到数据库,则上述代码应该适合您.

最好的祝福

原文地址:https://www.jb51.cc/csharp/97556.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐