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身份验证登录凭据,如果使用该帐户成功连接到数据库,则上述代码应该适合您.

最好的祝福

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...