[英]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();
}
}
}
SQL Connection引发了无效的操作异常。
“无效操作。连接已关闭”。
这是我的完整代码。 在另一个程序中,它完美无缺。
这是第二次,这不起作用。 我正在使用VS2005 ...也许我的程序已损坏?
堆栈跟踪:
在System.Data.SqlClient.SqlConnection.GetOpenConnection()
在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 Statement
,它将自动处理您的SQL连接。
另请检查: 在MSDN上使用ADO.NET的最佳实践
其他事项:使用SQL Management Studio并尝试使用连接字符串中的sql身份验证登录凭据,如果使用该帐户成功连接到数据库,则上述代码应该适合您。
最好的祝福
代码应该读取
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
...
}
尝试添加此代码。 您可能已打开连接,而在重新运行程序时,您尝试再次打开连接,或者您遇到服务器或连接字符串问题
con.Close();
有关更多信息,请访问http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx
你可以在打开之前检查连接状态 :
SqlConnection con = new SqlConnection(connectionString);
if (con.State==ConnectionState.Closed)
{
con.Open();
}
// here your code goes for sql operations
con.Close();
尝试使用using
语句。 在大型数据库的情况下直接手动打开和关闭数据库是个坏主意。
using(SqlConnection con = new SqlConnection(connectionString))
尝试这样做以打开和关闭连接>>
public DB(string conStr):base()
{
con = new OracleConnection(conStr);
con.Open();
}
public void Close()
{
con.Close();
//con.Dispose();
}
希望有帮助。
我遇到了同样的问题,我在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()
但总时间是200秒,所以我不得不在我的WebService
WebConfig
中更改它:
<system.web>
<httpRuntime executionTimeout="600" /> <!--10 min-->
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.