Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

sql server - C# console application Invalid Operation Exception

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();
        }
    }
}

The SQL Connection threw a invalid operation exception.

"Invalid Operation. The connection is closed".

This is my complete Code. In a other program, it works perfect.

That is the second time, that doesnt work. Im working with VS2005...maybe my program is damaged?

Stacktrace:

at System.Data.SqlClient.SqlConnection.GetOpenConnection()
at System.Data.SqlClient.SqlConnection.get_ServerVersion()

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The correct way doing that should be something like:

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 Using Statement it will automatically dispose your SQL connection.

Check this also: Best Practices for Using ADO.NET on MSDN

Other things to do: Use SQL Management Studio and try to use your sql authentication login credential from your connection string and if you have successfully connected to your database using that account the above code should work for you.

Best Regards


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...