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 连接引发了无效操作异常.
The SQL Connection threw a invalid operation exception.
无效操作.连接已关闭".
这是我的完整代码.在其他程序中,它运行完美.
This is my complete Code. In a other program, it works perfect.
这是第二次了,不行.我正在使用 VS2005...也许我的程序已损坏?
That is the second time, that doesnt work. Im working with VS2005...maybe my program is damaged?
堆栈跟踪:
在 System.Data.SqlClient.SqlConnection.GetOpenConnection()
在System.Data.SqlClient.SqlConnection.get_ServerVersion()
at System.Data.SqlClient.SqlConnection.GetOpenConnection()
at System.Data.SqlClient.SqlConnection.get_ServerVersion()
正确的做法应该是这样的:
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 Statement
它会自动处理你的 SQL 连接.
Using Using Statement
it will automatically dispose your SQL connection.
也检查一下:在 MSDN 上使用 ADO.NET 的最佳实践
要做的其他事情:使用 SQL Management Studio 并尝试使用连接字符串中的 sql 身份验证登录凭据,如果您已使用该帐户成功连接到数据库,则上述代码应该适合您.
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.
最好的问候
这篇关于C# 控制台应用程序无效操作异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!