SQL Server 2008 connection with C# - c#

No matter what I try I keep getting the following error when I try to run a simple select query to the database I created (I've run the exact query in the Management studio and it works fine and the login used is in the sysadmin group):
{"Cannot open database \"Test\" requested by the login. The login
failed.\r\nLogin failed for user
'JackLarson'."} System.SystemException
{System.Data.SqlClient.SqlException}
My connection string is:
Data Source=.\MPIT_TEST;Initial Catalog=Test;Integrated
Security=True;Connect Timeout=30;User Instance=True

you have to set your server name in your connection string
if your servername is SERVERSQLCOMPUTER your connection string will be:
Data Source=SERVERSQLCOMPUTER \MPIT_TEST;Initial Catalog=[Test_MPITRACKER];Integrated Security=True;Connect Timeout=30;User Instance=True
Moreover, always specify server name to be able to use your application on every computer in network entreprise (servername\serverinstance is an absolute path)
.\serverinstance means that your application is on the same computer than your Sql server

Take a look at the error message. It says it cannot find database named Test although you specified Test_MPITRACKER in the connection string. It looks like there is an issue when you have a database with undescore _ character in its name.
The easiest way would be to remove the undescore from the name of the database.
If you want to use database name with the underscore character, try to wrap it with square brackets, so it looks like this:
Data Source=.\MPIT_TEST;Initial Catalog=[Test_MPITRACKER];Integrated Security=True;Connect Timeout=30;User Instance=True
However, I haven't tested this solution, it's based on information found here: Database created in SQL Server Management Studios cannot be found by Visual Studio 2010.
EDIT
According to the conversation in the comments this is not the cause of the issue in this case.

Related

Connection string error - Sql Express

I am trying to connect to my local database(Sql Express) in Visual Studio to the Application Forms button. In Server Explorer and properties, connection string is:
connectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Work\Documents\Visual Studio 2015\Projects\MyTest\MyTest\Database.mdf";Integrated Security=True;Connect Timeout=30";
All the guides I've been reading use following connection string:
connectionString = "Data Source=localhost\\SQLExpress;Initial Catalog=Databasen;User ID=admin;Password=password";
But when inserting this string path in my button in Form1, and press button, an error appears - couldn't open connectionSystem.Data.SqlClient.SqlException (0x80131904):
Could someone explain the difference and which one of them should be used and why? And how i'm able to use the last connection example.
The top one is for a SQL data file connect that's located here: C:\Users\Work\Documents\Visual Studio 2015\Projects\MyTest\MyTest\Database.mdf
connectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Work\Documents\Visual Studio 2015\Projects\MyTest\MyTest\Database.mdf";Integrated Security=True;Connect Timeout=30";
The second is to a local database. Make sure the name of the sever "localhost" is correct. Also I noticed in your database name you have 'Databasen' is this correct spelling. Check user name and password too.
connectionString = "Data Source=localhost\\SQLExpress;Initial Catalog=Databasen;User ID=admin;Password=password";
Please explain what you are doing when you say
But when inserting this string path in my button in Form1, and press button, an error appears - couldn't open connectionSystem.Data.SqlClient.SqlException (0x80131904)
You should never put the connection string in your user interface.
If you need to know how to connect through code we can show you.

Windows Service SQL Server error - "Login failed for user"

I have a Windows Service written in C# being run on a Windows Server 2012 R2 machine which connects to a remote SQL Server 2012 instance also on a Windows Server 2012 R2 Server.
The SQL Connection String is defined in the App Config as follows:
<connectionStrings>
<add name="destinationConnectionString" providerName="System.Data.SqlClient"
connectionString="Server=10.42.42.10;Database=mydb;User ID=myuser;Password=mypass" />
</connectionStrings>
When running the service, the output error log shows:
System.Data.SqlClient.SqlException (0x80131904): Login failed for user
'myuser'.
Error Number:18456, State:1, Class:14
So I check the SQL Server Logs to find out more information about the error and find this
Login failed for user myuser Reason: Password did not match for the
login provided"
Source: Logon Message: Error: 18456, Severity: 14, State: 8.
The problem is I know these credentials are correct. I've checked and double checked.
I am able to prove the credentials work by opening SQL Server Management Studio on the source machine, and connecting to the remote SQL Server using the exact same Server, User ID and Password with "SQL Server Authentication" authentication mode.
In fact I have 2 different users that I'm able to connect with using SSMS, but that fail using the Windows service. If I am able to connect to the remote machine using mixed mode auth directly in SSMS. Why not in my Windows service?
I'm at a loss here, could anyone suggest what the issue might be?
Edit: I can even successfully connect to the remote machine using the following command:
sqlcmd -S 10.42.42.10 -U myuser -P mypass -d mydb
The proper syntax for specifying the initial database is:
Server=10.42.42.10;Initial Catalog=mydb;User ID=myuser;Password=mypass
My best guess is that it is ignoring the "Database" in your string and possibly trying to connect to the default database setting for the login (possibly master maybe?) and doesn't have at least public role to it. Although I've found out that "Database" is a valid alternative.
It's possible there is a character in your password that is tripping it up. Semicolons and equal signs will be particularly problematic. Try putting double quotes around your User ID and Password like:
Server=10.42.42.10;Initial Catalog=mydb;User ID="myuser";Password="mypass"
If there's a quotation mark in your password you will have to replace it with two of them for each occurrence.
Once you get your connection string built, then you have to ensure that it will parse properly in XML. Which means escaping control characters and the other special characters such as:
< with <
> with >
& with &
' with &apos;
" with "
If you open up your app config file in a browser it should show you if it looks proper.
I recommend adding the contents of your entire connection string to our output log of your service. That way you can see what it looks like. At the point before you attempt to open the connection, get it with:
string connStr = ConfigurationSettings.AppSettings("myConnectionString");
Then output the connStr value to the log. It will show you what values are being used at least.
You might use some special character in password, that is reserved for XML. If so, you'll need to use escape character as a replacement.
For instance, if your password is PASS<WORD the valid entry in config file would be: PASS<WORD
I have used this site to find the correct pattern
What you have is valid:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
Are you trying to connect to an instanced sql server? Server=10.42.42.10/SomeInstance
I suggest adding the semicolon, ;, after the password in the connection string. Perhaps it's being parsed weirdly.
I also wonder whether: is a semicolon in your actual password?
Maybe you're attempting a Windows account but there's also a SQL account named the same way. If so, make sure you prefix the Windows account with the domain name. E.g. you might have Windows account of MYDOMAIN\sa with P#ssword, whilst SQL server account is sa and its password is P#ssw0rd.
To make sure what accounts exists, log in the SQL server as an admin and check what accounts are listed under "Security" node of both the server itself and the database of interest.
I had the same problem and here is my solution:
I found out that I was using named instance of an SQL server and changed Server of my connection string from Server=localhost to Server=localhost\SQLEXPRESS and everything worked just fine for me! :)

Invalid value for key attachdbfilename C#

I'm using this tutorial to create my first SQL Server database which is linked with my C# Windows form application. However when I compile my application in VS 2012 I get the following error:
"Invalid value for key attachdbfilename".
This is my connection string:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\bin\Debug\Calculations.mdf;Integrated Security=True
I have searched many sites to resolve my problem but it's still persisting and I'm running out of ideas.
PS: In the connection string Calculations.mdf is my database name.
At AttachDbFilename should be the path to your mdf file.
Replace (LocalDB)\v11.0 by ., so it should be like this :
Data Source=.;AttachDbFilename=|DataDirectory|\bin\Debug\Calculations.mdf;Integrated Security=True
For your AttachDbFilename value, instead of using |DataDirectory|\bin\Debug\Calculations.mdf, try to give a full path like "C:\Project\Calculations.mdf". Because you can't verify that your path is correct with your current method.

Is there a universal connection string for different computers to connect to a local database using my program developed by vs2010

newbie here.
I have a local db in my program. Whilst I was developing the program I used the SQL
Connection string :
SqlConnection sconn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\leemk_000\Documents\......Integrated Security=True;User Instance=True;");
Now If I want to load this program onto a different computer I am sure that this connection will no longer work simply because it will still be looking for Users\Lee_000\
I have tried to remove Lee_000 but I get this following error:
An attempt to attach an auto-named database for file C:\Users\Documents..... failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
What can I do to get a connection string to work on different computers.
With many thanks
The whole User Instance and AttachDbFileName= approach is flawed - at best - especially when you want to share your database amongst multiple clients!
When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. YourDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
If it's a local db you should be placing it within the app folder and carry it with the app right?
Put the database in the App_data folder of your app and use that in your connection string
<add name="YourConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\yourfile.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
You need to use a database server and let your users use it via your connection string like this;
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
"myServerAddress" should be the ip adress of your server machine.

Connection string for remote SQL server 2008 without SQL Management Studio

I know its a classic problem, but I am too novice to even comprehend the basics (sorry). I have this ASP.NET "Website" with databases (SQL Server 2008), which I am trying to deploy on a Remote Host Server (HostGator) using WebSite Copy tool of VS 2010.
In VS 2010, I could grab the Connection string directly through the "property" of the database, which turned out to be:
Data
Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\myName\Documents\Visual
Studio 2010\WebSites\Experiment\App_Data\data.mdf";Integrated
Security=True;User Instance=True
Now, I know that a website called http://connectionstrings.com/ exists, but its too overwhelming for me at first glance.
My current connection string:
Data
Source=domainName.com\SQLEXPRESS;AttachDbFilename=C:\inetpub\vhosts\domainName\httpdocs\Experiment\App_Data\data.mdf;Integrated
Security=True;User Instance=True
I am pretty sure, that this is wrong as its giving me the classic error of:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server..
But I don't know how to fix it. Where to start looking, how to initiate, how to get the parameters required to build the connection string. How to find the path of the AttachDbFilename ? Can you please help?
I believe, that connection string is the only parameter which needs to be modified. If there's something else, then please suggest? Also, I keep coming across the usage of SQL Management Studio to make things work, I don't have that, so is it hard to accomplish this without it?
Please help, thanks.
You can't specify a directory relative to your own machine.
Change AttachDbFilename to
AttachDbFilename=|DataDirectory|data.mdf
The specifics for Data Source should be given to you from your hosting company, as well the security model (probably you need to use a specific user)
You can download SqlServer Management Studio Express from this link
Man,
What do you think about HttpServerUtility.MapPath Method. It returns the physical file path that corresponds to the specified virtual path on the Web server.
[]'s
When you get your hosting. They will provide the connection string for you. like this
<add name="ConnectionStringName"
connectionString="Data Source=localhost;Database=YourDatabaseName;Uid=YourUserNameForDatabase;password=yourpassword;"
providerName="System.Data.SqlClient" />
Let me know, if you need more help

Categories