Syntax Error near Insert Statement - vb.net

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 :)

Related

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

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.

ExecuteReader: CommandText property has not been initialized when trying to make a register form for my database

hello guys im trying to script a register form for my database and i came with this code >> so can anyone help ?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
Else
MsgBox("Already registered")
End If
End Sub
Edit your Code in this way..
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Insert will not retrieve any records it's a SELECT statement you want to use .I'll suggest you use stored procedures instead to avoid Sql-Injections.
ExecuteReader it's for "SELECT" queries, that helps to fill a DataTable. In this case you execute command before cmd.commandText is defined.
You should have define cmd.commandText before and use ExecuteNonQuery after, like this.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()
cn.Close()
cmd.CommandText should be assigned stored proc name or actual raw SQL statement before calling cmd.ExecuteReader
Update:
Change code as follows
....
cmd.Connection = cn
cmd.CommandText = "select * from TblToRead where <filter>" ''This is select query statement missing from your code
cn.Open()
dr = cmd.ExecuteReader ....
where <filter> will be something like username = "' & Request.form("username') & '" '
The error itself is happening because you're trying to execute a query before you define that query:
dr = cmd.ExecuteReader
'...
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Naturally, that doesn't make sense. You have to tell the computer what code to execute before it can execute that code:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
'...
dr = cmd.ExecuteReader
However, that's not your only issue...
You're also trying to execute a DataReader, but your SQL command doesn't return data. It's an INSERT command, not a SELECT command. So you just need to execute it directly:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
cmd.ExecuteNonQuery
One value you can read from an INSERT command is the number of rows affected. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Dim affectedRows as Int32 = cmd.ExecuteNonQuery
At this point affectedRows will contain the number of rows which the query inserted successfully. So if it's 0 then something went wrong:
If affectedRows < 1 Then
'No rows were inserted, alert the user maybe?
End If
Additionally, and this is important, your code is wide open to SQL injection. Don't directly execute user input as code in your database. Instead, pass it as a parameter value to a pre-defined query. Basically, treat user input as values instead of as executable code. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES(#Username,#Password)"
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = TextBox2.Text
(Note: I guessed on the column types and column sizes. Adjust as necessary for your table definition.)
Also, please don't store user passwords as plain text. That's grossly irresponsible to your users and risks exposing their private data (even private data on other sites you don't control, if they re-use passwords). User passwords should be obscured with a 1-way hash and should never be retrievable, not even by you as the system owner.
You're attempting to change the CommandText after you're executing your query.
Try this:
Private cn = New SqlConnection("Server=localhost;Database=test;UID=sa;PWD=secret")
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.CommandText = "select * from table1" ' your sql query selecting data goes here
Dim dr As SqlDataReader
cmd.Connection = cn
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows = 0 Then
InsertNewData(TextBox1.Text, TextBox2.Text)
Else
MsgBox("Already registered")
End If
End Sub
Private Sub InsertNewData(ByVal username As String, ByVal password As String)
Dim sql = "INSERT INTO User_Data(Username,Password) VALUES(#Username, #Password)"
Dim args As New List(Of SqlParameter)
args.Add(New SqlParameter("#Username", username))
args.Add(New SqlParameter("#Password", password))
Dim cmd As New SqlCommand(sql, cn)
cmd.Parameters.AddRange(args.ToArray())
If Not cn.ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cn.Close()
End Sub
This code refers the INSERT command to another procedure where you can create a new SqlCommand to do it.
I've also updated your SQL query here to use SqlParameters which is much more secure than adding the values into the string directly. See SQL Injection.
The InsertNewData method builds the SQL Command with an array of SQLParameters, ensures that the connection is open and executes the insert command.
Hope this helps!

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

No Value Given for one or more required parameters

I'm trying to get this update command to work. I have a table in access that has two fields, and I'm just trying to update the second one. I have code like this already in my program and it worked - I can't figure out why this code doesn't work:
Private Sub Button9_Click(sender As System.Object, e As System.EventArgs) Handles Button9.Click
Try
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BuddyMatching.accdb;Persist Security Info=False")
Dim cmd1 As New OleDb.OleDbCommand("Update Priorities set priorityDesc = '" & ComboBox12.Text & "' where priorityNum =1", conn)
Dim cmd2 As New OleDb.OleDbCommand("Update Priorities set priorityDesc = '" & ComboBox13.Text & "' where priorityNum =2", conn)
Dim cmd3 As New OleDb.OleDbCommand("Update Priorities set priorityDesc = '" & ComboBox14.Text & "' where priorityNum =3", conn)
conn.Open()
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
cmd3.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Every time I run this code, I get "No value given for one or more required parameters" returned via the MsgBox. My ComboBoxes are not inputting null values, so that's not it. Hopefully another set of eyes will spot the issue.
Thanks!

SELECT statement with JOIN and WHERE clause not returning any data

I have problem with data that needs to be seen on datagridview. Bellow is my code:
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim CONNECT_STRING As String = (...)
Dim cnn As New OleDbConnection(CONNECT_STRING)
cnn.Open()
MsgBox(status_narocila.value)
Dim sql As String = "SELECT artikel.st_artikla, artikel.naziv_artikla, narocilo.kolicina, narocilo.barva_tiska, narocilo.izvedba, narocilo.opombe, narocilo.datum_narocila, narocilo.rok_izdelave, narocilo.status, narocilo.ID FROM (narocilo INNER JOIN artikel ON narocilo.id_artkla = artikel.ID) WHERE(narocilo.ID = '" & status_narocila.value & "')"
Dim cmd As New OleDbCommand(sql, cnn)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds, "artikel")
cnn.Close()
DataGridView1.DataSource = ds.Tables("artikel")
End Sub
End Class
Value status.narocila.value is integer, I've tested it and getting right value from it. The code is working fine without WHERE clause.
= '" & status_narocila.value & "')"
should be
= " & status_narocila.value & ")"
no ' on numeric data types.
If narocilo.ID is also an integer, then the problem is you're using text qualifers on an integer field.
Try changing your WHERE clause to:
WHERE(narocilo.ID = " & status_narocila.value & ")"