Update Access database using Visual Studio 2015 - VB.net - vb.net

I am trying to do a simple update to an Access 2016 database. I am using Visual Studio/VB.net. I have been able to do this already on a different form with no issues using the same type of coding (it's pretty basic, it was for a school project but not anymore). I have tried two different ways to do this...using the update table adapter, for example:
MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
AvailabilityTextBox.Text, EmailTextBox.Text)
Using that method I always get a notImplemented exception thrown even though I have used a similar type of adapter elsewhere. Also I tried using a strung method (I know, not ideal):
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
But this method gives me the error of Syntax Error in UPDATE statement. Again I have used this method elsewhere with no problems. Below I will post all the code for this form.
Imports System.Data
Imports System.Data.Odbc ' Import ODBC class
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class editMediators
Dim NewData As Boolean
Dim objConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ECRDatabase.accdb")
' create functions for save or update
Private Sub runAccessSQL(ByVal sql As String)
Dim cmd As New OleDbCommand
connect() ' open our connection
Try
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Close()
MsgBox("Data Has Been Saved !", vbInformation)
Catch ex As Exception
MsgBox("Error when saving data: " & ex.Message)
End Try
End Sub
Private Sub editMediators_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.MediatorsListTableAdapter.Fill(Me.ECRDatabaseDataSet.mediatorsList) 'loads current mediator information
DateTimePicker1.Value = Today()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'update button
NewData = True
alertMsgBox2()
End Sub
Private Sub alertMsgBox2()
Select Case MsgBox("Yes: Saves Changes," & vbNewLine &
"No: Exits the mediator update window without saving," & vbNewLine &
"Cancel: Returns to the mediator update window.", MsgBoxStyle.YesNoCancel, "Update Mediator Information")
Case MsgBoxResult.Yes
MediatorsListBindingSource.EndEdit()
updateMediator()
'intentionally commented out
'MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
'AvailabilityTextBox.Text, EmailTextBox.Text)
' Me.Close()
Case MsgBoxResult.No
MediatorsListBindingSource.CancelEdit()
Me.Close()
End Select
End Sub
Private Sub updateMediator()
Dim saveInfo As String
If NewData Then
Dim Message = MsgBox("Are you sure you want to update mediator information? ", vbYesNo + vbInformation, "Information")
If Message = vbNo Then
Exit Sub
End If
Try
'Update mediator information
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
Catch ex As Exception
End Try
Else
Exit Sub
End If
runAccessSQL(saveInfo)
End Sub
There is obviously something I am missing, though I am not sure it is missing from the code. I checked my database fields and set them to string/text fields just to see if I could get it working. At one time, I had two 2 phone number fields that were set to to the wrong data type so you could only enter a number per int32 requirements. I actually had one of these methods working/updating the db several months ago but I can't figure out what happened since. I do know Visual Studio gave me some problems which probably contributed but it's been too long to remember what happened.
I am rather lost on what else to try as this seems like it should work one way or another. Any ideas what to look at and/or try?? Hopefully I can be pointed in the right direction.
Thanks :)

Your update statement is incorrect, the WHERE clause is inside the VALUES() segment, and should be after it.
Try this instead:
(Edited)
saveInfo = "UPDATE mediatorsList SET mediatorName='" & _
MediatorNameTextBox.Text & "', email='" & EmailTextBox.Text & "', .... WHERE " & _
mediatorID = '" & MediatorIDTextBox.Text & "'"
Also be sure to handle the date correctly. I usually force formatting in yyyy/mmm/dd format.

Related

object reference not set to an instance of the object Error when adding data into my database

I am having a problem when i am trying to put this data into my database
I'm using Vstudio 2013 and MS Access as my database
my problem is everytime i click add to add the data in my database this error always popping object reference not set to an instance of the object. even i declared the
Here's my Add button Code
Dim cn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
cmd.Connection = cn
cmd.CommandText = "INSERT INTO gradess ( StudentNo,StudentName,StudentSection,SubjectNo1,SubjectNo2,SubjectNo3,SubjectNo4,SubjectNo5,SubjectNo6,SubjectNo7,SubjectNo8,TotalAverage) " & "Values('" & txtStudentNo.Text & "','" & lblName.Text & "','" & lblSection.Text & "','" & txtSubject1.Text & "','" & txtSubject2.Text & "','" & txtSubject3.Text & "','" & txtSubject4.Text & "','" & txtSubject5.Text & "','" & txtSubject6.Text & "','" & txtSubject7.Text & "','" & txtSubject8.Text & "','" & lblTotalAverage.Text & "')"
cmd.ExecuteNonQuery()
refreshlist()
disablebutton()
MsgBox("Successfully Added!!", vbInformation, "Successful")
clear()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
When you declare a variable like Dim cn As OleDb.OleDbConnection you are just telling the compiler what type it is not creating an object of that type.
When you use the New keyword OleDb.OleDbConnection is not just the name of a class (the data type) but it is an actual method. It is calling the constructor of the class which returns an instance of the object.
In C# you are required to put the parenthesis after like OleDb.OleDbConnection() which shows you are calling a method. You can add the parenthesis in vb.net but it is not required but I think it is a good reminder of the difference between setting a data type and creating an object.
Your declaration should be : Dim cn As New OleDb.OleDbConnection Dim cmd As New OleDb.OleDbCommand
– F0r3v3r-A-N00b 20 mins ago

Having trouble inserting data to mysql datetimepicker [duplicate]

This question already has answers here:
How to compare two dates FORMATS for saving to DB
(3 answers)
Closed 6 years ago.
How do you insert data into the database using datetimepicker in VB.NET? I tried to convert it using:
Format(name_of_the_datetimepicker.Value, "yyyy-MM-dd") in my SQL statement but I don't know where did I go wrong.
Here is my code:
Imports MySql.Data.MySqlClient
Public Class frmMain
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Not conn Is Nothing Then
conn.Close()
End If
conn = New MySqlConnection("Data Source=" & Server & ";user id=" & UserName & ";password=" & PassWord & ";database=" & DatabaseName & ";")
Try
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
Dim cmdSave As MySqlCommand
Dim sql As String
sql = "INSERT INTO (rental_date, inventory_id, customer_id, return_date, staff_id) VALUES ('" & Format(dt_picker_rental_date.Value, "yyyy-MM-dd") & "', '" & txt_inventory_id.Text & "', '" & txt_customer_id.Text & "', '" & Format(dt_picker_return_date.Value, "yyyy-MM-dd") & "', '" & txt_staff_id.Text & "')"
Try
cmdSave = New MySqlCommand(sql, conn)
cmdSave.ExecuteNonQuery()
MsgBox("Success!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
DO NOT use string concatenation to insert data into SQL code. ALWAYS use parameters. Parameters maintains all data in binary form so format is never an issue. More importantly, you are protected from SQL injection. Using a date, that could look like this:
Dim command As New MySqlCommand("INSERT INTO MyTable (DateColumn) VALUES (#DateColumn)", connection)
command.Parameters.AddWithValue("#DateColumn", myDateTimePicker.Value)
If you want to insert just the date without the time then use Value.Date instead of just Value.
More info on ADO.NET parameters here:
http://jmcilhinney.blogspot.com.au/2009/08/using-parameters-in-adonet.html
Try this. It may help you.
cmd.Parameters.Add("date", OleDbType.DBDate).Value = DateTimePicker1.Value

Could not find file "...\bin\Debugdb.mdb" when trying to open an Access .mdb file

I'm trying to make a very simple application that connects to an Access 2003 database.
I built a very simple user interface with 7 labels and 7 text-box with only 2 buttons: one of them is "Save" and the other one is "Exit".
Inside my form I added the code :
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
'Try
Dim saveinto As New OleDb.OleDbCommand
Dim constr As String = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "db.mdb"
Dim conn As New OleDb.OleDbConnection(constr)
saveinto.Connection = conn
saveinto.CommandType = CommandType.Text
saveinto.CommandText = " insert into users(id,username,nid,money,mode,help,yesorno) " & " values ('" & TextBox7.Text & "' ,'" & TextBox1.Text & "' , '" & TextBox2.Text & "','" & TextBox3.Text & "' , '" & TextBox4.Text & "' , '" & TextBox5.Text & "' , '" & TextBox6.Text & "')"
conn.Open()
saveinto.ExecuteNonQuery()
conn.Close()
MsgBox("All Done :P ")
Exit Sub
End Sub
when i press the Save Button i got that error :
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll`
and its the first time to see it, i thought that something wrong in my system (WinVista:) or database (build with my Access 2007 then converted to 2003) and i uninstall Access 2007 and install 2003 then rebuild new database and replace the old one with it.
When i run my app and press the Save Button i got the same error Message with
OledbException was unhandled Could not find file 'C:\Users\Mahmoud\Documents\Visual Studio 2008\Projects\Test\Test\bin\Debugdb.mdb.
i searched here before asking my question for my problem but i couldn't find the same problem and and i tried to apply some suggestions from similar errors but nothing happened so forgive me if duplicated a question and please HELP.
thanks
It appears that Application.StartupPath returns
C:\Users\Mahmoud\Documents\Visual Studio 2008\Projects\Test\Test\bin\Debug
and that does not have a trailing backslash (\), so when you append db.mdb to it you get a path that does not actually point to your database file. Try
... Application.StartupPath & "\db.mdb"
instead.

SQL Program UPDATE Record Error

I'm working in a small SQL Database program. The programs just there to view, edit and update the database records. Everything is working remarkably well considering I've never tried something like this before. I've managed to get the Add Records, Refresh Records and Delete Records functions working flawlessly. However, I've hit a little bump when trying to UPDATE a selected record.
To clarify, the SQL Table is displayed in a list view, from this list view the end-user can select a particular-record and either edit or delete it.
The edit button opens a new form window with text fields which are automatically filled with the current information of that record.
The code for the edit record form is:
Private Sub frmEdit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
intDB_ID_Selected = CInt(frmMain.lvRec.SelectedItems(0).Text)
Call dispCaption()
Call dispInfo() 'Display the info of the selected ID
End Sub
Private Sub dispInfo()
SQL = "Select * from PersonsA " & _
"where Members_ID=" & intDB_ID_Selected & ""
With comDB
.CommandText = SQL
rdDB = .ExecuteReader
End With
If rdDB.HasRows = True Then
rdDB.Read()
Me.midtxt.Text = rdDB!Members_ID.ToString.Trim
Me.gttxt.Text = rdDB!Gamer_Tag.ToString.Trim
Me.sntxt.Text = rdDB!Screenname.ToString.Trim
Me.fntxt.Text = rdDB!First_Name.ToString.Trim
Me.lntxt.Text = rdDB!Last_Name.ToString.Trim
Me.dobtxt.Text = rdDB!DoB.ToString.Trim
Me.dobtxt.Text = rdDB!DoB.ToString.Trim
Me.emailtxt.Text = rdDB!E_Mail_Address.ToString.Trim
Me.teamptxt.Text = rdDB!Position.ToString.Trim
Me.ugctxt.Text = rdDB!Cautions.ToString.Trim
Me.recordtxt.Text = rdDB!Record.ToString.Trim
Me.eventatxt.Text = rdDB!Event_Attendance.ToString.Trim
Me.Mstattxt.Text = rdDB!Member_Status.ToString.Trim
End If
rdDB.Close()
End Sub
Private Sub dispCaption()
End Sub
Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
Call disControl()
'Validation
If invalidUpdateEntry() = True Then
Call enaControl()
Exit Sub
End If
'Prompt the user if the record will be updated
If MsgBox("Are you sure you want to update the selected record?", CType(MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2 + MsgBoxStyle.Question, MsgBoxStyle), "Update") = MsgBoxResult.Yes Then
'Update query
SQL = "Update PersonsA" & _
"SET Members_ID='" & Me.midtxt.Text.Trim & "'," & _
"Gamer_Tag='" & Me.gttxt.Text.Trim & "'," & _
"Screenname='" & Me.sntxt.Text.Trim & "'," & _
"First_Name='" & Me.fntxt.Text.Trim & "'," & _
"Last_Name='" & Me.lntxt.Text.Trim & "'," & _
"DoB='" & Me.dobtxt.Text.Trim & "'," & _
"E_Mail_Address='" & Me.emailtxt.Text.Trim & "'," & _
"Position='" & Me.teamptxt.Text.Trim & "'," & _
"U_G_Studio='" & Me.ugptxt.Text.Trim & "'," & _
"Cautions='" & Me.ugctxt.Text.Trim & "'," & _
"Record='" & Me.recordtxt.Text.Trim & "'," & _
"Event_Attendance='" & Me.eventatxt.Text.Trim & "'," & _
"Member_Status='" & Me.Mstattxt.Text.Trim & "'" & _
"WHERE Members_ID='" & intDB_ID_Selected & "'"
Call execComDB(SQL) 'Execute the query
Me.Close()
'*** Refresh the list
SQL = "Select * from PersonsA "
Call frmMain.dispRec(SQL)
'--- End of refreshing the list
Exit Sub
Else
Call enaControl()
End If
End Sub
As I've said, I've been able to do everything else using an extremely similar method, but when I try to UPDATE the record I get an error saying
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'Members_ID'.
I know it's this line that's the problem
"WHERE Members_ID='" & intDB_ID_Selected & "'"
Call execComDB(SQL) 'Execute the query
But referencing 'intDB_ID_Selected' has always worked before, and it's been set-up on the update form records load as intDB_ID_Selected = CInt(frmMain.lvRec.SelectedItems(0).Text)
I know this is a huge thread but if anyone could steer me in the right direction WITHOUT telling me to re-write the entire statement I'd be forever grateful.
EDIT1: I fixed the comma before the WHERE clause, but I'm still getting the same error.
Missing a space between
"Update PersonsA " & _
"SET Members_ID= ....
and (as already pointed out) a comma not needed before the WHERE
Said that, do a favor to yourself and to your users. Do not use string concatenation to build a sql command. Use always a parameterized query.
Just as an example
SQL = "Update PersonsA SET Members_ID=#id, Gamer_Tag=#tag, Screenname=#screen," & _
"First_Name=#fname,Last_Name=#lname,DoB=#dob,E_Mail_Address=#email," & _
"Position=#pos,U_G_Studio=#studio,Cautions=#caution,Record=#rec," & _
"Event_Attendance=#event, Member_Status=#stat " & _
"WHERE Members_ID=#id"
SqlCommand cmd = new SqlCommand(SQL, connection)
cmd.Parameters.AddWithValue("#id", Me.midtxt.Text.Trim)
..... so on for the other parameters defined above ....
cmd.ExecuteNonQuery();
Change "Member_Status='" & Me.Mstattxt.Text.Trim & "'," & _
to "Member_Status='" & Me.Mstattxt.Text.Trim & "'" & _
Looks like it was just an extra rogue comma!
On any error like this, use debugging provided with Visual Studio. Inspect the value of SQL, paste into MS SQL Management Studio - it has syntax highlight, and you should be able to spot the error easily.
To prevent further issues (including SQL injection vulnerability), separate this query into an embedded resource, and use parameters. Then it's easy to view, maintain (you can copy/paste between SQL Mgmt Studio and VS), and ultimately use it in code.
A side note, you don't need to use Call in VB.NET, just put a method name with parenthesis.

UPDATE statement failing when attempting to update access database - VB.Net

I am trying to create a simple ticketing software for myself with a VB.Net front end and an Access 2003 back end. I have with allowing new rows to be added, but when I try to code the Update row button, it is giving me the error that says Microsoft JET Database Engine - Syntax error in UPDATE statement. I cannot find what the problem is.
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim ConnectString As String = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\aaron-pister\Desktop\New Role Notes\Issue Tracker Express\Issue Tracker Express\Issue Tracker.mdb")
Dim con As New OleDbConnection(ConnectString)
con.Open()
Dim Green42 As String = "UPDATE Issues Basic Details SET [Company Name] = '" & txtClientName.Text & "', [Status] = '" & cbStatus.Text & "', [Company Contact] = '" & txtClientContact.Text & "', [Description] = '" & txtDesc.Text & "', [Notes] = '" & txtRes.Text & "' WHERE [TicketNum] = '" & txtTicket.Text & "'"
'con.Open()
If txtClientName.Text <> "" Then
Try
'MyCom.CommandText = "UPDATE [Issues Basic Details] SET Company Name = '" & txtClientName.Text & "', Status = '" & cbStatus.Text & "', Company Contact = '" & txtClientContact.Text & "', Description = '" & txtDesc.Text & "', Notes = '" & txtRes.Text & "' WHERE TicketNum = '" & txtTicket.Text & "')"
da = New OleDbDataAdapter(Green42.ToString, ConnectString)
da.Fill(dt)
da.Update(EsInfo1, "Issues Basic Details")
MsgBox("Your record has been updated successfully.", MsgBoxStyle.DefaultButton1, "New Ticket Submitted")
Catch ex As Exception
MsgBox(ex.Source & "-" & ex.Message)
con.Close()
Exit Sub
End Try
Else
MsgBox("You must have an entry in the Client Name, Client Contact and Status fields. It is recommended to also have a value in the Description field.", MsgBoxStyle.OkOnly, "Issue Tracker Express")
btnNewIncident_Click(sender, e)
Exit Sub
End If
End Sub
Your table name has to be bracketed too:
Dim Green42 As String = "UPDATE [Issues Basic Details] SET [Company Name]..."
Also, use parameters instead of putting the values into the string. It avoids SQL Injection.
This:
UPDATE Issues Basic Details SET ...
Is not valid SQL. You need to help it by qualifying your table name:
UPDATE [Issues Basic Details] SET ...
A few other suggestions:
Use prepared statements (parameterize your SQL to avoid SQL injection attacks)
Don't define this type of behavior in a click event handler -- have a helper class to do this work so it can be re-used and isn't coupled directly to the UI.
Use Using statements. Your OleDbConnection class implements IDisposable. You aren't properly disposing this connection.
While it's hard to read your code at the moment, it does look like you are trying to do an "AdHoc" query, which can cause a lot of problems.
I'd recommend first changing your statement to a parameterized query to help diagnose issues too.