user3197661
user3197661

Reputation: 47

Can't Insert data to database ms-access vb

Case 1: i can't insert data to my database

  Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ProjectVB.accdb")

Case 2: i can insert data to my database

Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Admin\Documents\ProjectVB.accdb")

database was saved in my project already

conn.Open()

            cmd.Connection = conn
            cmd.Parameters.AddWithValue("@ac_ID", txtID.Text)
            cmd.Parameters.AddWithValue("@ac_pass", txtPassword.Text)
            cmd.Parameters.AddWithValue("@nation_ID", txtNoID.Text)
            cmd.Parameters.AddWithValue("@fName", txtFirstName.Text)
            cmd.Parameters.AddWithValue("@lName", txtLastName.Text)
            cmd.Parameters.AddWithValue("@tel", txtTel.Text)
            cmd.Parameters.AddWithValue("@province", cbNation.SelectedItem)
            cmd.Parameters.AddWithValue("@regOn", dtRegOn.Text)
            cmd.Parameters.AddWithValue("@status", txtStatus.Text)
            cmd.Parameters.AddWithValue("@gender", cbGender.SelectedItem)
            cmd.Parameters.AddWithValue("@location", txtLocation.Text)
            cmd.Parameters.AddWithValue("@img", imgBuffer)
            cmd.Parameters.AddWithValue("@rank", cbRank.SelectedItem)
            cmd.CommandText = "INSERT INTO db_KJ_Profile VALUES(@ac_ID,@ac_pass,@nation_ID,@fName,@lName,@tel,@province,@regOn,@status,@gender,@location,@img,@rank)"
            cmd.ExecuteNonQuery()

Upvotes: 0

Views: 926

Answers (1)

Steve
Steve

Reputation: 216363

In the case of the DataDirectory substitution string you should check the content of the database in the folder PROJECTFOLDER\BIN\DEBUG (or x86 version of the same path).

This is due to the fact that in a WinForms application, when running in a debug session of VS, the DataDirectory points to the folder where your application is executed (The BIN\DEBUG or BIN\x86\DEBUG subfolder of the project folder).

This is easy to overlook and it is always a source of confusion.
And it is worse if you have the ACCDB file listed in your project items. In this case the database item has a property called Copy To The Output Directory. You should check that is set to Copy If Newer or Copy Never and not to Copy Always because in this case, at every restart of your debug session a new copy of the database is copied (of course without the just inserted data) from your project folder to the BIN\DEBUG folder

Upvotes: 2

Related Questions