Reputation: 3485
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 trackat 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?
Upvotes: 3
Views: 2272
Reputation: 19272
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;
Upvotes: 3
Reputation: 755197
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.
Upvotes: 5