I created a database in SQL Server Management Studio and I called it SalonDatabase. I tried to connect to the database in VS C#. For this I created two connectionString and only one of them work so I would like to know why.
This one works:
string connString = #"Data Source=.\SQLEXPRESS;initial catalog=SalonDatabase;Integrated Security=SSPI";
However, the following does not work even though I know for a fact that the file is located in that directory
string connString = #"Data Source=.\SQLEXPRESS;
Initial Catalog=C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\SALONDATABASE.MDF;Integrated Security=SSPI";
The error I'm getting is :
Cannot open database "C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\SALONDATABASE.MDF" requested by the login. The login failed. Login failed for user 'USER-PC\USER'
Now I logged in as administrator in my computer. I also read about the user instances in SQL server but I don't see that is the reason why the second connection fails.
The database is created using SQL Server Management Studio so do not use AttachDBFileName. You may use Server Explorer (from View Menu) tool of Visual Studio to obtain the connection string.
Add connection From Server-Explorer + Right mouse click on Data Connections + Add Connection + Select Microsoft Sql Server Data Source (change).
After adding connection, right mouse click to select/open properties windows.
Data Source=.\sqlexpress;Initial Catalog=SalonDatabase;Integrated Security=True
Modify your connection to 'attach' your mdf. Given that your .mdf path has spaces, be sure to enclose it in single quotes.
Server=.\SQLExpress;
AttachDbFilename='C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\SALONDATABASE.MDF';
Database=dbname;
Integrated Security=SSPI;
Trusted_Connection=Yes;
Initial Catalog is used to set the Default Database name when we Connect to a Server.
when you are passing the complete path of the database file the connection String makes a search for a database with name C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\SALONDATABASE.MDF
which actually does not exists therefore it fails.
you can use the initial approach and if you want to use full path then AttachDbFilename can be used as suggested by P.Campbell
By default, when working with SQL Server (any edition), the server part handles all the file-related chores for you. You just create a new database (or attach an existing one) and give it a logical database name and then you refer to that database solely via this database name - you don't care (and don't need to) about the actual files that make up your database.
That's why your first connection string works - you're telling SQL Server (Express) that you want to work with a database called SalonDatabase and SQL Server knows which files this concerns.
Microsoft introduced this notion of being able to "dynamically" create a user-instance of SQL Server Express and attaching a physical .MDF file (instead of referring to a database by logical name) as a developer tool to make things easier - but quite frankly, in my opinion, it's a rather messy concept and has lots of drawbacks.
In this scenario, you basically tell SQL Server in your connection string (using AttachDbFileName=salondatabase.mdf and with User Instance=True) that it should start a separate instance of SQL Server Express for your user context, and automagically attach that physical MDF file specified as its database, and provide you access to that.
As mentioned by another comment, it's a deprecated feature - SQL Server 2012 will bring a new, hopefully slicker concept of local databases. So in my opinion, you should try to avoid using this feature - it's more trouble than anything else.
Related
I created an MVC4 solution in VS 2012 with EF5, and right now I am trying to get the database to be created Code First. In the Create method of the controller I added db.Database.CreateIfNotExists();
On my machine, I also have SQL Server 2012 running, and I would like the db to be created there instead of in some SQL Express engine or other lightweight solution.
I have tried several approaches to making a correct connection string, but all has failed, and now I have no idea as to how it should look. This is how it looks now, but nothing gets created, and all i get from the CreateIfNotExists is an error:
InnerException {"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)"} System.Exception {System.Data.SqlClient.SqlException}
This is what my connection string looks like:
<add name="Tool.Models.Context" connectionString="Server=MSSQLSERVER;Initial Catalog=Tool.models.ToolDb.mdf;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
EDIT:
After struggling with this issue for almost a day, I resolved it by substituting localhost for MSSQLSERVER (Which still is the name of the instance if I look at the Configuration Manager). Thanks for the comments though. Made me think.
localhost is the local server, not the instance, you appear to be using the default instance (called mssqlserver) and so don't need to specify the instance name, just the server name, hence why substituting MSSQLSERVER with localhost in your connection string works.
You could also use the actual name of the server in here, e.g. SERVER-01 (or whatever the actual name of your particular DB server is) and it would have the same effect.
If however you had installed a named instance on the machine, you would have to specify both the server name and the instance, e.g. localhost\instancename or server-01\instancename
Hope this helps explain why putting in localhost works.
That's right...
By default, as most may already be aware, Visual Studio 2012 - ASP.NET MVC 4 templates
will define a Default connectionString that points to a (LocalDb)v11.0 in Web.config.
In the case of Visual Studio 2010 ASP.Net MVC 4 project templates, it pointed to SQLExpress...
In my case I prefer pointing the connectionString to a specific SQL Server 2012 I use for dev.
So let's say I open SQL Management Studio and see SQLServer2012-01 name in a droplist where I want the database + tables to be created,
well that's the name I'd normally use...
connectionString="Server=SQLServer2012-01; InitialCatalog=..."
All you have to do afterwards is straightforward - follow the steps in defining
-Enable-Migrations
-[fill your Seed method with content - if needed...]
-Add-Migration MyFirstMigration [or any migration name you want]
-Update-Database -Verbose
and you should see results updated in Server Explorer Window.
Hope it helps
I moved a database from a hosted SQL Server 2008 to SQL Server 2012 on a dedicated server.
I created the database, and copied a table using the Import/Export Wizard. And I changed the connection string in the application to point to the new database.
The application seems to be able to connect, but when I do a select or insert I get the error :
"System.Data.SqlClient.SqlException: Invalid object name '...' ".
When I put the same connection string in the SQL Management Studio it connects and works fine.
What could cause this???
you may check web.config that if it doesn't contain more than one connection string or you have to make connection by using VS interface then you can easily test connection and this automatically writes connection you web.config
I have checked the instance name, auto close is set to true, allow remote connections on the server is checked. The server is running when I open the SQL Server configuration manager. I have even rebooted. I have created this db the same way as all others. I use Entity Framework and have checked the names in the web.config and they match. This is the default connection string from the wizard - I use for testing before I deploy. I just can't think of anything else to check to figure out why it won't connect. Working inside SQL Server everything is fine.
Here is the general 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: Shared >Memory Provider, error: 40 - Could not open a connection to SQL Server)
Config:
connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string='data source=.\SQL_1;attachdbfilename="C:\Program Files (x86)\Microsoft SQL Server\MSSQL10_50.SQL_1\MSSQL\DATA\A_db.mdf";integrated security=True;connect timeout=10;user instance=True;multipleactiveresultsets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
Thanks in advance.
Let me preface this answer by saying that proper setup of a SQL instance is not as easy as Microsoft would like you to think with the entity framework. It's a little bit involved and requires that you put your DBA hat on for a little bit.
The error you have indicates that the web instance is attempting to connect to the SQL server using Windows Integrated Security. This will work fine if (a) the windows user that the process is running as (which can be configured in IIS) is authorized to log on to the SQL server and has a valid login in the database and (b) if the SQL server is on the same machine or in the same domain as the IIS server.
In light of this, I recommend using SQL Server authentication. If you need to know how to do this, I recommend searching for "SQL Server Authentication setup" - here is an article that I found which might help you set this up.
http://msdn.microsoft.com/en-us/library/aa337562.aspx
In general, I recommend taking the following actions:
Connect to the sql server using MS SQL Management Studio.
Permanently attach your database, then use the Initial Catalog property on your connection string rather than AttachDbFileName
Then set up your login username and password on the SQL server, and create a login in the database for it.
Make sure your login can only execute the stored procedures you want it to execute. Deny it access to running sql statements.
You will also need to add the username and password to your connection string, and set IntegratedSecurity=false.
Let us know how things go once you get your SQL server set up properly.
This error means that your provider code cannot find the SQL Server. If you have checked the server instance name (it should be <yourLocalServer>\SQL_1), then it could be the attachdbfilename= parameter, as this is a really unreliable way to specify the database to connect to (you should be using the Database Name, not the file name), because there are about a hundred reasons that the file name could change that have nothing to do with your application.
I'm trying to generate my database tables from my Entity Framework model, but I'm getting this error when I execute the generation query:
Database 'Database' does not exist. Make sure that the name is entered correctly.
I'm able to connect to the local server just fine.
My connection string, which was generated by VS when I selected 'Database.mdf':
metadata=res://*/Models.Models.csdl|res://*/Models.Models.ssdl|res://*/Models.Models.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
The database definitely exists, but I've noticed that the only databases it's picking up on the server are called master, model, msdb and tempdb.
Can anyone help?
Edit: I've just realised that the SQL connection dialog that comes up when you click "Execute SQL" allows you to connect to a server. But my DB isn't on a server, it's just a user instance database. But that's the only option, so how would I execute against my database? I have the database open in the 'Server Explorer'.
The connection string is referring to a user instance database is that what you intended? I got the impression possibly not from the question.
If not try changing it to Data Source=ServerName\InstanceName;Initial Catalog=Database;Integrated Security=True;
If you are using a user instance database, specify the full path to the location of the database with USE directive.
For example:
USE [C:\Project\Database.mdf]
GO
When connecting the server, you need to select another data source, then enter the name of the local server on which the database is located.
I can't speak for Entity Framework, but within SQL, "database" is a (very) reserved word. Try calling your database (and it's files) something else, even if just "MyDatabase".
I faced such problem when running a script in SQL Server Management Studio to do some stuff on my Local SQL Server. I noticed that the Query Window that I was running the script in was connected to a Remote SQL Server not my local machine.
Is it possible to access a Visual Studio 2008-created server-based database from a VB-6 application? If not, what is the best way to share a database between a VB-6 application and a C# application?
If you are referring to the SQL Server Express database that comes with Visual Studio 2008, you can access that with plain old ADO.
The connection strings for doing this are at http://connectionstrings.com/sql-server-2005. The most appropriate one is probably this one:
Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;
Uid=myUsername;Pwd=myPassword;
For SQL Server Express (which is what comes with VS2008), don't miss the server name syntax Servername\SQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2005 Express installation resides.
The reference for programming against a SQL Server database using ADO is here:
http://msdn.microsoft.com/en-us/library/aa905875(SQL.80).aspx
Example for connecting to the SQL Server database is below (untested). Note that this one uses SQL Server authentication rather than Windows Authentication. Check your connection strings on http://www.connectionstrings.com. If SQL Native Client doesn't work, try one of the others.
' Initialize variables.
Dim cn As New ADODB.Connection
Dim connectionString As String
' Specify the OLE DB provider.
cn.Provider = "{SQL Native Client}"
' Specify connection string on Open method.
connectionString = Server=myMachineName\SQLEXPRESS;Database=myDataBase; _
Uid=myUsername;Pwd=myPassword;
cn.Open connectionString
I just added a "Service-based database" to a project. I go the following in my app.config, in the configuratonStrings element:
<add name="SerializeToSql.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
I don't know if ADO has user instance support. if it does, then you may be able to create
an equivalent connection string for ADO to use. Otherwise, you'll need to just create a "normal" database in SQL Server Express. You should be able to use that from ADO.
In order for other machines to see your SQL Express instance, you need to make sure it allows remote connections, the SQL Browser service is turned on, and is allowed through the firewall.
Fire up the SQL Server 2005 Surface Area Configuration tool: All Programs->Microsoft SQL Server 2005->Configuration Tools->SQL Server Surface Area Configuration.
Click Surface Area Configuration for Services and Connections
Click the 'Remote Connections' node and select 'Local and remote connections'. If you want to refer to the server as ServerName\MSSQLSERVER, you'll have to user named pips or TCP/IP and named pipes.
Click the SQL Server Browser node. Change the Startup type to Automatic and start the service.
For the firewall, make sure you make an exception for the SQL Server program (C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe) and for the SQL Server Browser program (c:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe)