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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15566277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:11:32  来源:igfitidea点击:

C# console application Invalid Operation Exception

c#sql-serverconsoleinvalidoperationexception

提问by mnlfischer

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.

SQL 连接引发了无效操作异常。

"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?

那是第二次,那不起作用。我正在使用 VS2005...也许我的程序损坏了?

Stacktrace:

堆栈跟踪:

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

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

采纳答案by BizApps

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 Statementit will automatically dispose your SQL connection.

使用Using Statement它会自动处理您的 SQL 连接。

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

另请检查:在 MSDN 上使用 ADO.NET 的最佳实践

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.

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

Best Regards

此致

回答by Jacek

Try add this code. You probably has open connection and while rerun program you try to again open connection or you have problem with server or your connection string

尝试添加此代码。您可能已打开连接,并且在重新运行程序时尝试再次打开连接,或者服务器或连接字符串有问题

con.Close();

See there for more info http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx

有关更多信息,请参阅http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx

回答by Arshad

you can check connection statebefore opening ittry this :

你可以在打开之前检查连接状态试试这个:

SqlConnection con = new SqlConnection(connectionString);
if (con.State==ConnectionState.Closed)
{                      
    con.Open();   
}

// here your code goes for sql operations

con.Close();

回答by Freelancer

Try to use usingstatements. Direct manually opening and closing data bases in case of large databases is bad idea.

尝试使用using语句。在大型数据库的情况下直接手动打开和关闭数据库是个坏主意。

using(SqlConnection con = new SqlConnection(connectionString))

Try to do like this for open and close connections>>

尝试为打开和关闭连接这样做>>

public DB(string conStr):base()
{
con = new OracleConnection(conStr);
con.Open();
}


public void Close()
{
con.Close();
//con.Dispose();

} 

Hope Helpful.

希望有帮助。

回答by Thorsten Dittmar

The code should read

代码应该读

using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();

    ...
}

回答by Dani

I was having same problem, my solution in VB is:

我遇到了同样的问题,我在 VB 中的解决方案是:

Dim db As New Database

' ... Some Work with EF without procedures (90 seconds)

db.SaveChanges()

For Each p In list

    If db.Database.Connection.State <> ConnectionState.Open Then
        ' This is only executed 1 time
        db.Database.Connection.Open()
    End If

    ' ... Some Work with EF but calling a mapped procedure (1 or 2 seconds each call)
    db.MyProcedure(p.FieldId)

Next

db.Dispose()

But the total time was 200 seconds, so I had to change this in my WebConfigof my WebService:

但总时间是 200 秒,所以我不得不在我WebConfigWebService

<system.web>
    <httpRuntime executionTimeout="600" /> <!--10 min-->
...