C#控制台应用程序无效的操作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连接引发了无效的操作exception。
“操作无效。连接已关闭”。
这是我的完整代码。 在另一个程序中,它完美无缺。
这是第二次,这不起作用。 我正在使用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身份validation登录凭据,如果使用该帐户成功连接到数据库,则上述代码应该适合您。
最好的祝福
尝试添加此代码。 您可能已打开连接,并且在重新运行程序时,您尝试再次打开连接,或者您遇到服务器或连接字符串问题
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(); }
希望有帮助。
代码应该是读
using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); ... }