简体   繁体   中英

Creating database in SQL Server Express using SMO

I'm trying to create a database in SQL Server Express using WinForms and C#

Here is what I'm trying to do

Microsoft.SqlServer.Management.Smo.Server srv = new Microsoft.SqlServer.Management.Smo.Server srvServer();
int i = srv.Databases.Count;

just to get the count at the start. But I get the error

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) this is the stack track

at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
at Microsoft.SqlServer.Management.Common.ConnectionManager.get_ServerVersion()
at Microsoft.SqlServer.Management.Smo.ExecutionManager.GetServerVersion()
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.GetDbComparer(Boolean inServer)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.InitializeStringComparer()
at Microsoft.SqlServer.Management.Smo.AbstractCollectionBase.get_StringComparer()
at Microsoft.SqlServer.Management.Smo.SimpleObjectCollectionBase.InitInnerCollection()
at Microsoft.SqlServer.Management.Smo.SmoCollectionBase.get_InternalStorage()
at Microsoft.SqlServer.Management.Smo.SmoCollectionBase.InitializeChildCollection(Boolean refresh)
at Microsoft.SqlServer.Management.Smo.SmoCollectionBase.get_Count()
at CreateDB.CreateDB.btnCreateDB_Click(Object sender, EventArgs e) in C:\\Users\\Guest1\\Downloads\\CreateDB\\CreateDB\\CreateDB.cs:line 82

What should be done?

If you're using SQL Server Express , and you've installed with all the defaults, then your server instance will be called .\\SQLEXPRESS . You need to use that in your code:

using Microsoft.SqlServer.Management.Smo;

Server srv = new Server(".\\SQLExpress");
int i = srv.Databases.Count;

If you create a new Server instance without specifying an instance name, it tries to connect to the default instance (with no name) - which you don't have, if you've installed just SQL Server Express.

First make the connection by using the SqlConnection object. you should do this

SqlConnection conn = new SqlConnection(@"Data Source=.\SQLExpress;Initial Catalog=master;Integrated Security=True");
Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(new ServerConnection(conn));
int i = server.Databases.Count;

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