Monday, April 13, 2009

Connection String Troubles

Having trouble nailing down your connection string for a database you're trying to connect to a Windows Form?

I did. 

I was looking over a bit of code that was intended to connect a Windows Form to a database containing user login information. The connection string looked like this:

String sconn;
sconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\Owner\\Desktop\\Royal Gas Station\\Royal Gas Station\\bin\\Debug\\Users.mdb";

But of course, this path won't work after we deploy the application. After all, we're not going to deploy it on the client's computer in a debugging folder on their desktop. After a bit of research, I turned up an interesting little snippet that retrieves the path at which the app has been deployed. Knowing this, I fixed the connection string and now it looks like this:

String sconn;
sconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Databases\\Users.mdb";

Next time you're having trouble with the path, USE RELATIVE instead of ABSOLUTE, and make use of the |DataDirectory| alias.