Error - Number of query values and destination fields are not the same.' - vb.net

Please help in below code error shows:
Number of query values and destination fields are not the same.
Dim constring As String = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" &
Application.StartupPath & "\db_billing.accdb;Persist Security Info=True")
Using con As New OleDb.OleDbConnection(constring)
Using cmdd As New OleDb.OleDbCommand("insert into tlbitems values(#Estimate_Number,#Service_Procedure_Name,#Amount)", con)
cmdd.Parameters.AddWithValue("#Estimate_Number", row.Cells("Serial_Number").Value)
cmdd.Parameters.AddWithValue("#Service_Procedure_Name", row.Cells("Service").Value)
cmdd.Parameters.AddWithValue("#Amount", row.Cells("Total").Value)
con.Open()
cmdd.ExecuteNonQuery()
con.Close()
End Using
End Using
Next
MessageBox.Show("Saved")
End Sub

Specify the columns names in your insert query like below:
Using cmdd As New OleDb.OleDbCommand("insert into tlbitems(Estimate_Number, Service_Procedure_Name, Amount)
values(#Estimate_Number,#Service_Procedure_Name,#Amount)", con)
This is just an example, you should put the correct column names from your table tlbitems defination.

Related

Syntax Error near Insert Statement

I am trying to insert data in Access database but getting a Syntax error exception :( What am I doing wrong ?
Private Sub savebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles savebtn.Click
Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\vb8\Mini-project\Mini-project\mini_db.mdb")
Dim query As String
Try
con.Open()
query = "INSERT INTO minitab VALUES (" & TextBox1.Text & "," & TextBox2.Text & ",#dob ," & TextBox5.Text & "," & TextBox6.Text & "," & TextBox7.Text & "," & TextBox8.Text & "," & TextBox9.Text & ")"
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(query, con)
Dim dt As New DataTable
da.Fill(dt)
MsgBox("Data has been saved", MsgBoxStyle.SystemModal, "ok")
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
You are adding values in your Insert statement without addressing the columns. Now, this is not necessary if you put the values in the correct order so I suggest you to check it again. However, if you specify the column names then your insert statement might look like:
"INSERT INTO minitab(column1,Column2,Column3)VALUES(#col1,#col2,#col3)",connectiontring
cmd.Parameters.Add("#col1",OleDbType.VarChar).Value = TxtBox1.Text 'make sure to set the datatype correctly
cmd.Parameters.Add("#col2",OleDbType.VarChar).Value = TxtBox2.Text
.........
cmd.ExecuteNonQuery
And most importantly, what are you trying to do? If you are trying to insert data, then why are you using a DataTable? The code above will let you insert data into the database. However, a datatable is used to get data from the database and display it. Also DataTables have change tracking and are used in conjunction with DataAdapters to perform CRUD operations.
However, to use a DataTable to display data, you can try this:
Dim cmd as new OleDbCommand("Select * from minitab",connectionstring)
Dim dt as new DataTable
Dim ada as new OleDbDataAdapter(cmd)
ada.Fill(dt)
To display the data, you can use various controls. One of them is a DataGridView.
DataGridView1.DataSource = dt
Hope you understand :)

.NET OleDb parameterized query not working as expected

I'm trying to pass this Update command to a database, it completes ok with no errors but it doesnt update the database and I can't understand why?
Dim Cmd As OleDbCommand
Dim SQL As String
Dim objCmd As New OleDbCommand
Dim Con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Settings.MasterPath)
Dim Item = "08/08/2015"
SQL = ("UPDATE [Hol Dates] SET [" & EmployeeList.Text & "]= #Htype WHERE [HDate]=#Hdate")
Cmd = New OleDbCommand(SQL, Con)
objCmd = New OleDbCommand(SQL, Con)
objCmd.Parameters.AddWithValue("#Hdate", item)
objCmd.Parameters.AddWithValue("#Htype", "None")
Con.Open()
Dim ans = MsgBox("Do you want to unbook this holiday?", MsgBoxStyle.YesNo)
If ans = MsgBoxResult.Yes Then
objCmd.ExecuteNonQuery()
Else
Exit Sub
End If
Con.Close()
Con.Dispose()
You need to reverse the order in which you add the parameters to the OleDbCommand object. OleDb allows us to assign names to parameters but it ignores the names and only pays attention to the order in which the parameters appear in the CommandText.
Therefore, since your SQL statement refers to Htype and then Hdate you need to add the parameters in that same order.

How to insert listview items into 3 different tables VB.net

I'm trying to make a library system. I have a listview and it contains items to be inserted into different tables, (b_borrow_tbl, for the books , d_borrow_tbl for the multimedia, and m_borrow_tbl for the module).
I'm using this code to insert items to b_borrow_tbl:
Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()
For xa = 0 To ListView1.Items.Count - 1
Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(#bid,#user,#dateborrowed,#admin ,'" & "Borrowed" & "')", myconnection)
mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
mycommand.Parameters.AddWithValue("user", selecteduser)
mycommand.Parameters.AddWithValue("dateborrowed", datestring)
mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
mycommand.ExecuteNonQuery()
myconnection.Close()
Next
MsgBox("Transaction Saved")
ListView1.Items.Clear()
myconnection.Close()
End Sub
Here's one possibility. Note that I can't give you exact code because I don't know the structure of your other tables...so, with that caveat...
Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()
For xa = 0 To ListView1.Items.Count - 1
Dim itemType as String
itemType = ListView1.Items(xa).Subitems(6).Text ' Not sure abt col #
if itemType="Books" Then
Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(#bid,#user,#dateborrowed,#admin ,'" & "Borrowed" & "')", myconnection)
mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
mycommand.Parameters.AddWithValue("user", selecteduser)
mycommand.Parameters.AddWithValue("dateborrowed", datestring)
mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
mycommand.ExecuteNonQuery()
End If
If itemType="Multimedia" Then
mycommand.SqlCommand="Insert into d_borrow_table( field1,field2,etc) values (#parm1,#parm2,...)
mycommand.Parameters.Clear()
mycommand.Parameters.AddWithValue("#param1",value)
' etc
mycommand.ExecuteNonQuery()
' Then repeat by changing command text for third table
' clearing/defining parameters, then executing the query
End If
myconnection.Close()
Next
MsgBox("Transaction Saved")
ListView1.Items.Clear()
myconnection.Close()
End Sub
All we're doing here is "resetting" the "mycommand" variable with a new INSERT statement, clearing the parameters, and redefining them for the second and third inserts. Note that the connection isn't closed until after all three inserts have fired. You'll obviously need to replace the "placeholders" of "field1,field2" and #param1,#param2 etc with the actual fields from your tables, but I think that should give you a push in the right direction.

Adding data from Text boxes directly to database and viewing updated gridview

still very new to this and can't seem to find exactly what I'm looking for. Quick run-through on what I'm trying to accomplish. I have a datagridview (3 columns - Id, Name, Address) that is connected to a local .mdf database file, that I'm able to search through using a search textbox. My goal NOW is to submit records into the database directly using 2 text fields and the Id field to automatically increment. (Id++, txtName.Text, txtAddress.Text) and to use a send button(btnSend) to activate this event.(PLEASE KEEP IN MIND, MY GOAL IS TO HAVE EVERYONE INCLUDING THE NEW RECORD SHOW UP IN THE DATAGRIDVIEW AND FOR THE NEW ROW TO BE INSERTED DIRECTLY TO THE DATABASE AND SAVE ANY CHANGES) I've been hammering at this for a couple days now and would appreciate any help. Below is my code, but please keep in mind I'm still new and trying to figure this language out so if there's any unnecessary code, please do let me know... Also if you want to help with one additional thing, maybe some code on how to export that table to a different file from an export button. Thanks! I'm currently also getting an error saying "Cannot find table 0." when I click the btnSend button.
Public Sub btnSend_Click(ByVal sender As Object, e As EventArgs) Handles btnSend.Click
Try
Dim connectionString As String
Dim connection As SqlConnection
Dim ds As New DataSet("Table")
Dim dataset As New DataSet()
Dim sqlInsert As String
Dim sqlSelect As String
Dim Id As Integer = 5
Dim newRow As DataRow = dataset.Tables(0).NewRow()
connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=""" & My.Application.Info.DirectoryPath & "\Database1.mdf"";Integrated Security=True;"
sqlInsert = "INSERT INTO Table (#Id, #Name, #Address) VALUES (" & Id & ", '" & txtName.Text & "','" & txtAddress.Text & "')"
sqlSelect = "SELECT * FROM Table"
connection = New SqlConnection(connectionString)
Dim da As New SqlDataAdapter()
connection.Open()
da.Fill(ds)
Using da
da.SelectCommand = New SqlCommand(sqlSelect)
da.InsertCommand = New SqlCommand(sqlInsert)
da.InsertCommand.Parameters.Add(New SqlParameter("Id", SqlDbType.Int, 4, Id))
da.InsertCommand.Parameters.Add(New SqlParameter("Name", SqlDbType.NText, 50, txtName.Text))
da.InsertCommand.Parameters.Add(New SqlParameter("Address", SqlDbType.NText, 50, txtAddress.Text))
Using dataset
da.Fill(dataset)
newRow("Id") = Id
newRow("Name") = txtName.Text
newRow("Address") = txtAddress.Text
dataset.Tables(0).Rows.Add(newRow)
da.Update(dataset)
End Using
Using newDataSet As New DataSet()
da.Fill(newDataSet)
End Using
End Using
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Throw New Exception("Problem loading persons")
End Try
Dim updatedRowCount As String = gvDataViewer.RowCount - 1
lblRowCount.Text = "[Total Row Count: " & updatedRowCount & "]"
End Sub

Insert new records into a table with Visual Basic using OLEDBConnection

I'm using Visual Basic 2010 Express and Access 2003.
I'm trying to make sql querys to the mdb file. I'm using OLEDBConnection. The Select query works fine, but I can't insert rows in the table. Here is the code.
Dim connStr As String = "provider=Microsoft.Jet.OLEDB.4.0;data source=" & System.IO.Directory.GetCurrentDirectory() & "\tpv.mdb;"
Dim con As New OleDb.OleDbConnection(connStr)
con.Open()
Dim query As String = "select * from Productos"
Dim cmd As New OleDb.OleDbCommand(query, con)
Dim reader As OleDb.OleDbDataReader
reader = cmd.ExecuteReader
While reader.Read()
MsgBox(reader.GetValue(0) & ", " & reader.GetValue(1) & " , " & reader.GetValue(2))
End While
reader.Close()
query = "insert into Productos (NombreProducto,PrecioCoste) VALUES ('cana',4)"
Dim cmd2 As New OleDb.OleDbCommand(query, con)
cmd.ExecuteNonQuery()
con.Close()
Why the INSERT query does not work?
Ok, I found my stupid problem.
Althoug I have declared 2 OleDbCommands, I referenced the first one in both cases