我遇到的情况对我来说很奇怪。虽然我已经找到了另一种更简单的方法来使我的代码工作,但我很想知道为什么会发生这种情况。以下是完美无缺的代码:
public DataHelper()
{
this.dataSource = "MyMachine";
this.initCatalog = "myDB";
this.uid = "sa";
this.pass = "thep@ssw0rd";
this.conStr = "Data Source=" + dataSource + ";Initial Catalog=" + initCatalog + ";User ID=" + uid + ";Password=" + pass;
this.conn = new SqlConnection(conStr);
}
毋庸置疑,这是默认构造函数,conn
是SqlConnection
的实例。
但是当我使用其他构造函数定义时:
public DataHelper(string constr)
{
this.conStr = constr;
this.conn = new SqlConnection(conStr);
}
我发现连接无法打开,应用程序崩溃了这个错误:
System.Data.SqlClient.SqlException未处理
类= 14
错误码= -2146232060
的HResult = -2146232060
LineNumber上= 65536
消息=登录失败,用户' sa' 数= 18456
过程=""
服务器= MYMACHINE
Source = .Net SqlClient数据提供者
州= 1堆栈跟踪:
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity,SqlConnectionString connectionOptions,SqlCredential credential,Object providerInfo,String newPassword,SecureString newSecurePassword,Boolean redirectedUserInstance,SqlConnectionString userConnectionOptions,SessionData reconnectSessionData,DbConnectionPool pool,String accessToken,Boolean applyTransientFaultHandling ) 在System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions选项,DbConnectionPoolKey poolKey,Object poolGroupProviderInfo,DbConnectionPool池,DbConnection owningConnection,DbConnectionOptions userOptions) 在System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool池,DbConnection owningObject,DbConnectionOptions选项,DbConnectionPoolKey poolKey,DbConnectionOptions userOptions) 在System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject,DbConnectionOptions userOptions,DbConnectionInternal oldConnection) 在System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject,DbConnectionOptions userOptions,DbConnectionInternal oldConnection) 在System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject,UInt32 waitForMultipleObjectsTimeout,Boolean allowCreate,Boolean onlyOneCheckConnection,DbConnectionOptions userOptions,DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject,TaskCompletionSource
1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource
1 retry,DbConnectionOptions userOptions,DbConnectionInternal oldConnection,DbConnectionInternal& connection) 在System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection,DbConnectionFactory connectionFactory,TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource
1重试) 在System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1重试) 在System.Data.SqlClient.SqlConnection.Open() 在C:\ Users \ RGP \ documents \ visual studio 2015 \ Projects \ SampleWork \ SampleWork \ DataHelper.cs中的SampleWork.DataHelper.doSelect(String sql):第66行 位于C:\ Users \ RGP \ documents \ visual studio 2015 \ Projects \ SampleWork \ SampleWork \ DatabaseSetup.cs中的SampleWork.DatabaseSetup.btnDataLogin_Click(Object sender,EventArgs e):第55行 在System.Windows.Forms.Control.OnClick(EventArgs e) 在System.Windows.Forms.Button.OnClick(EventArgs e) 在System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) 在System.Windows.Forms.Control.WmMouseUp(消息& m,MouseButtons按钮,Int32点击) 在System.Windows.Forms.Control.WndProc(消息& m) 在System.Windows.Forms.ButtonBase.WndProc(消息& m) 在System.Windows.Forms.Button.WndProc(消息& m) 在System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam) 在System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) 在System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32 reason,Int32 pvLoopData) 在System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason,ApplicationContext context) 在System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason,ApplicationContext context) 在C:\ Users \ RGP \ documents \ visual studio 2015 \ Projects \ SampleWork \ SampleWork \ Program.cs中的SampleWork.Program.Main():第18行 在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args) 在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args) 在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx) 在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态) 在System.Threading.ThreadHelper.ThreadStart()
如异常所述,下面是几行负责调用数据库连接的代码:
DatabaseSetup.cs
private void btnDataLogin_Click(object sender, EventArgs e)
{
string dbName = txtDbName.Text.Trim();
string uid = txtUid.Text.Trim();
string pass = txtPass.Text.Trim();
string machine = System.Environment.MachineName;
if (dbName.Length != 0 && uid.Length != 0 && pass.Length != 0)
{
string constr = "Data Source=" + machine + ";Initial Catalog=" + dbName + ";Persist Security Info=True; User ID=" + uid + ";Password=" + pass;
MessageBox.Show(constr);
//DataHelper helper = new DataHelper();//This works
DataHelper helper = new DataHelper(constr);//Doesn't work
helper.doSelect("select * from abc");
}
DataHelper.cs:
行为不同的doSelect(string sql)
并根据构造函数定义抛出异常:
public SqlDataReader doSelect(string sql)
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
return reader;
}
虽然我还检查了断点,但在执行doSelect()
期间连接字符串没有任何问题。
任何人都可以帮我理解这种情况吗?