简体   繁体   中英

C# Connect to local Microsoft SQL Server 2012 Database

I am having trouble connecting to a local Database running on the same machine as my C# code which is in Microsoft SQL Server 2012.

The SQL Server instance name is : MYINSTANCE The Database name is : MyDB

The code I am running is :

SqlConnection sqlConnection = null;
              //  MySqlConnection sqlConnection = null;
                try
                {
                    // Open Databse Connection
                    sqlConnection = new SqlConnection("Server=(localdb)\\MYINSTANCE;Database=MyDB;uid=Andy;password=pwd");

                    sqlConnection.Open();
                }  

When this runs an exception is caught which shows:

   Testing database connection ... [FAILED!]
   -> Database Connection Failed!
   Exception Caught: A network-related or instance-specific error occurred while
 establishing a connection to SQL Server. The server was not found or was not ac
cessible. Verify that the instance name is correct and that SQL Server is config
ured to allow remote connections. (provider: SQL Network Interfaces, error: 50 -
 Local Database Runtime error occurred. The specified LocalDB instance does not
exist.
)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception
, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObj
ect stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternal
ConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Bool
ean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFa
ilover)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSn
iOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirect
edUserInstance, SqlConnectionString connectionOptions, SqlCredential credential,
 TimeoutTimer timeout)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTime
r timeout, SqlConnectionString connectionOptions, SqlCredential credential, Stri
ng newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdent
ity identity, SqlConnectionString connectionOptions, SqlCredential credential, O
bject providerInfo, String newPassword, SecureString newSecurePassword, Boolean
redirectedUserInstance, SqlConnectionString userConnectionOptions)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOp
tions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConn
ectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)

   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConn
ectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbCon
nectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions
 userOptions)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOp
tions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection ow
ningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean o
nlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& co
nnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection ow
ningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbCon
nectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
 owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions
, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
 outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1
retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()

The database setup in the Server Management Studio looks like this:

在此处输入图片说明

Can somebody help me to understand what I am missing here?

So it appears you are confusing the system for connecting to LocalDb and the full blown SQL Server installation. Your connection string should look like this:

Data Source=.\MYINSTANCE;Initial Catalog=MyDB;User Id=Andy; Password=pwd; 

If your connection is failing with a message like `Login failed for user 'YOURPC\\Andy' then it's trying to use integrated security. You can force it now to by also specifying:

Integrated Security=false

If that doesn't work, try with integrated security turned on and not specifying username/password. This will use your Windows credentials to connect:

Data Source=.\MYINSTANCE;Initial Catalog=MyDB;Integrated Security=true;

尝试定义版本od localdb,例如:

(LocalDB)\v11.0

I am more comfortable with

sqlConnection = new SqlConnection("Data Source=.\\MYINSTANCE; Initial Cataog=MyDB; uid=Andy;password=pwd");

Let me know if this works or not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM