aarviii aarviii - 2 months ago 6x
Vb.net Question

setting database connection string

i'm using ms acces for my databse and i save it to the bin folder. what i want to do even when i transfer the project folder the program can still connect to the database.

Imports System.Data.OleDb
Public Class Form3

Dim con As New OleDb.OleDbConnection

Dim da As OleDbDataAdapter

Dim ds As New DataSet

Dim str1 As String

con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AARVIII\Documents\DATABASE\MP1.accdb"

please help me.


Your connection string locates your database in a fixed position valid only on your PC.
A simple workaround is to use the |DataDirectory| substitution string.

con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + 
                       "Data Source=|DataDirectory|\MP1.accdb"

in this way, you can control the location of your database through code.
Usually (for a desktop application) the |DataDirectory| substitution string points the same folder where you have installed your application, but you need to have permission to write there.

Instead you could change this location using code like this.

 Dim appFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
 Dim dbFolder = Path.Combine(appFolder, "MyAppFolder")
 AppDomain.CurrentDomain.SetData("DataDirectory", dbFolder)

Now the target directory for your database will be C:\programdata\myappfolder where your application has read/write permissions

More info on DataDirectory

Where is DataDirectory
DataDirectory where is documented