Can you set the datasource to a database as a string?

vanillah89

New member
Joined
Jun 10, 2015
Messages
1
Programming Experience
Beginner
I am working on a project and I am trying to allow the user to change the database location through the options menu. It worked for a xml file but I cant get it to work with a database.

How would I get the code to work like this? Is there anyway to accomplish this?

Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= strDBFilePath"

instead of an actual filepath

thanks
 
Hi vanillah89, you have a variable embedded in quotes which is incorrect, try:

Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDBFilePath

If your variable is correct, this should work.
 
A common way of doing that is to use String.Format() where you can "fill in the blanks":
Dim ConnString As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", strDBFilePath)
The {0} is simply a placeholder for the value you want to be put there, you can have a string with multiple of them, just increment the number with each one and include a variable or value for each one as a parameter after the string.
 
Use a connection string builder to build a connection string. E.g.
Dim builder As New OleDbConnectionStringBuilder

builder.Provider = "Microsoft.ACE.OLEDB.12.0"

MessageBox.Show(builder.ConnectionString)

builder.DataSource = "FirstDatabase"

MessageBox.Show(builder.ConnectionString)

builder.DataSource = "SecondDatabase"

MessageBox.Show(builder.ConnectionString)
 
Back
Top