简体   繁体   中英

Connecting to local SQL Server database from C# project

I am running Visual Studio 2017 with SQL Server Object Explorer. I have been unable to connect to a local SQL database, although I copied the connection string directly from the SQL Server properties window. I created a tiny test project just to work on making this connection work, but nothing I try is working. Any suggestions would be greatly appreciated.

My Connection String:

(localdb)\\MSSQLLocalDB;Initial Catalog=SportsStore;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

Error I am receiving:

Keyword not supported: '(localdb)\\mssqllocaldb;initial catalog'. at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) at System.Data.SqlClient.SqlConnection..ctor(String connectionString, SqlCredential credential) at System.Data.SqlClient.SqlConnection..ctor(String connectionString) at TestWebApp_Do tNetFramework.index.btnTestDBConn_Click(Object sender, EventArgs e) in c:\\users...

You need to add Data Source attribute too. Your connection string should be like this.

Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SportsStore;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

I wouldn't copy/paste connection strings directly from MS SQL Server Studio. If you want to connect to LocalDB, then this post is going to help How to connect to LocalDb

Your error code says:

Keyword not supported: '(localdb)\\mssqllocaldb;initial catalog'.

Which means that connection string parameter is mistype. if you want more information about connection string parameters, visit this link

try to add "Data Source = " in the begin of your string.

hope that help

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