Sorry if this is a really simple question, but I swear I have a)stared at it for a couple of days, and b) tried to google the answer.
I am using Visual Studio 2015, and I have added a database called Investments 4. I can connect to it using table adapters and a data grid and display data.
In another part of the program I am exploring SQL commands and trying to open the connection manually and then read data. I am trying to set up a new SqlConnection and I have picked up the connection string by right clicking the database in Server explorer and looking in properties which gives me the connection string.
However.... When I paste this connection string into the new instance command, VS objects because it contains quotation marks and backslashes.
Here's the line.
SqlConnection myConnection = new SqlConnection("Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = "C:\Users\Nick\Documents\Investments 4.mdf"; Integrated Security = True; Connect Timeout = 30");
myConnection.Open();
Clearly something simple and obvious wrong, but if someone could spare a couple of minutes to guide me, I would very much appreciate it.
You just need to escape the string. You can do so using the @ prefix:
SqlConnection myConnection = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = ""C:\Users\Nick\Documents\Investments 4.mdf""; Integrated Security = True; Connect Timeout = 30")
which means you just need to double up instances of ". Without using the @ prefix, you need to escape all the double quotes using the \ character, which also needs to be escaped itself:
SqlConnection myConnection = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\Nick\\Documents\\Investments 4.mdf\"; Integrated Security = True; Connect Timeout = 30")
When dealing with strings with file paths in - it's usually preferred to use the @ prefix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With