SqlClient support for LocalDB
Beginning in SQL Server 2012, a lightweight version of SQL Server, called LocalDB, is available. This article discusses how to connect to a LocalDB database.
Remarks
For more information about LocalDB, including how to install LocalDB and configure your LocalDB instance, see SQL Server Books Online.
To summarize what you can do with LocalDB:
Create and start LocalDB instances with sqllocaldb.exe or your app.config file.
Use sqlcmd.exe to add and modify databases in a LocalDB instance. For example,
sqlcmd -S (localdb)\myinst
.Use the
AttachDBFilename
connection string keyword to add a database to your LocalDB instance. When usingAttachDBFilename
, if you don't specify the name of the database with theDatabase
connection string keyword, the database is removed from the LocalDB instance when the application closes.Specify a LocalDB instance in your connection string. For example, your instance name is
myInstance
, the connection string would include:
server=(localdb)\\myInstance
User Instance=True
isn't allowed when connecting to a LocalDB database.
You can download LocalDB from Microsoft SQL Server 2012 Feature Pack. If you use sqlcmd.exe to modify data in your LocalDB instance, you need sqlcmd from SQL Server 2012, which you can also get from the SQL Server 2012 Feature Pack.
Programmatically create a named instance
Applies to: .NET Framework .NET Core .NET Standard
An application can create a named instance and specify a database as follows:
Specify the LocalDB instances to create in the app.config file, as follows. The version number of the instance should be the same as the version number of your LocalDB installation.
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="system.data.localdb" type="Microsoft.Data.LocalDBConfigurationSection,Microsoft.Data.SqlClient, Version=5.0.0.0, Culture=neutral, PublicKeyToken=23ec7fc2d6eaa4a5"/> </configSections> <system.data.localdb> <localdbinstances> <add name="myInstance" version="11.0" /> </localdbinstances> </system.data.localdb> </configuration>
Specify the name of the instance using the
server
connection string keyword. The instance name specified in theserver
connection string keyword must match the name specified in the app.config file.Use the
AttachDBFilename
connection string keyword to specify the .MDF file.