This question already has an answer here:
VB 2010 INSERT INTO syntax error
(1 answer)
Closed 6 years ago.
I have a program in VB.NET that will input data from textboxes into an Access database. Here is sample image:
This is the code I am using and it gives me an error:
m = TextBox1.Text
b = "'" + TextBox2.Text + "'"
x = "'" + TextBox3.Text + "'"
d = TextBox4.Text
n = "'" + TextBox5.Text + "'"
Dim s2 As String
s2 = "insert into users1 ( num , name1 , pass , add , phone ) " & " values ( " + m + " , " + n + " , " + b + " , " + x + " , " + d + " ) "
Dim cmd2 As New OleDbCommand(s2, con)
cmd2.ExecuteNonQuery()
The reason your SQL is failing is that "add" is a reserved word. i.e. you cannot use it without putting it in square brackets - [add]. As above you should parameterise your query, so one of these will work...
Using oleCmd As New OleDbCommand("Insert Into users1 (num,name1,pass,[add],phone) values (#num,#name1,#pass,#add,#phone)", con)
oleCmd.Parameters.Add("#num", OleDbType.Integer).Value = Textbox1.Text
oleCmd.Parameters.Add("#name1", OleDbType.VarChar).Value = Textbox2.Text
oleCmd.Parameters.Add("#pass", OleDbType.VarChar).Value = Textbox3.Text
oleCmd.Parameters.Add("#address", OleDbType.VarChar).Value = Textbox4.Text
oleCmd.Parameters.Add("#phone", OleDbType.Integer).Value = Textbox5.Text
oleCmd.ExecuteNonQuery()
End Using
Using oleCmd As New OleDbCommand("Insert Into users1 (num,name1,pass,[add],phone) Values (?,?,?,?,?)", con)
oleCmd.Parameters.AddWithValue("?", Textbox1.Text)
oleCmd.Parameters.AddWithValue("?", Textbox2.Text)
oleCmd.Parameters.AddWithValue("?", Textbox3.Text)
oleCmd.Parameters.AddWithValue("?", Textbox4.Text)
oleCmd.Parameters.AddWithValue("?", Textbox5.Text)
oleCmd.ExecuteNonQuery()
End Using
Note, it will fail if the data types do not match what you are trying to insert, so if you try to insert text in num or phone it will fail. You will need to validate your input and preferably convert them rather than use the textbox Text.
Related
So I am trying to update a database and a datagridview with a "save" button, I used the part of this code earlier in my program for another function, but here it is giving me a syntax error. Can anyone tell me where? I don't understand where it is.
This part of the code works when I add an employee.
Private Sub AddEmployee_Click(sender As Object, e As EventArgs) Handles AddEmployee.Click
Dim Msg, Style, Title, Response, mystring
Msg = "Do you want to add employee ?"
Style = vbYesNo + vbCritical + vbDefaultButton2
Title = "MsgBox Demonstration"
' Display message.
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
TableAdapterManager.UpdateAll(Database13DataSet)
con.Open()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Insert INTO dbo.employees (EmpID, LastName, FirstName, AddressHalf, SSN, VehNumb, Certification) values ('" + EmpID.Text + "' , '" + LastName1.Text + "', '" + FirstName1.Text + "', '" + AddyHalf1.Text + "', '" + SocialNum.Text + "', '" + VehNumb.Text + "', '" + Certification1.Text + "')"
cmd.Connection = con
cmd.ExecuteNonQuery()
MessageBox.Show("Employee Added")
Else
mystring = True
MessageBox.Show("Cancelled")
End If
con.Close()
This part of the code is the part that doesn't work. I think it has something to do with my coding trying to update a table but I cannot figure it out.
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
Dim Msg, Style, Title, Response, mystring
Msg = "Do you want to update employee ?"
Style = vbYesNo + vbCritical + vbDefaultButton2
Title = "MsgBox Demonstration"
' Display message.
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
TableAdapterManager.UpdateAll(Database13DataSet)
con.Open()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Update employees SET (EmpID, LastName, FirstName, AddressHalf, SSN, VehNumb, Certification) Where ( ModEmpID.Text , ModLastName.Text , ModFirstName.Text, ModAddy.Text , ModSSN.Text , ModVehNum.Text , ModCerts.Text )"
cmd.Connection = con
cmd.ExecuteNonQuery()
MessageBox.Show("Employee Added")
con.Close()
Else
mystring = True
MessageBox.Show("Cancelled")
End If
con.Close()
End Sub
Public Sub Updating()
Me.EmployeesTableAdapter.Fill(Me.Database13DataSet.Employees)
End Sub
End Class
If Response = vbYes Then
TableAdapterManager.UpdateAll(Database13DataSet)
con.Open()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Insert INTO dbo.employees (EmpID, LastName, FirstName, AddressHalf, SSN, VehNumb, Certification) values ('" + EmpID.Text + "' , '" + LastName1.Text + "', '" + FirstName1.Text + "','" + AddyHalf1.Text + "', '" + SocialNum.Text + "', '" + VehNumb.Text + "', '" + Certification1.Text + "')"
cmd.Connection = con
cmd.ExecuteNonQuery()
MessageBox.Show("Employee Added")
Else
Nooo.
It doesn't work like that; it was specifically intended not to work like that
You have tableadapters; nowhere at all, ever, in any of your code should there be "INSERT INTO.. or "UPDATE .., select, delete or any other kind of SQL
Let's have a real quick back-to-basics
At some point you've followed some tutorial that probably had you do something that caused a XyzDataSet.xsd file to appear in your project. Inside it there are datatables and tableadapters and the whole thing looks kinda like a database.
It's a local representation of a database; the table adapters download data from the database into the dataset's datatables; you manipulate the data/show the user/change it/add to it/delete from it..
..and when you're done you call upon the tableadapter to push it back to the database.
TableAdapters know how to do all that stuff you've put in your code; you can open the XyzDataSet.Designer.vb file and see it; it has thousands of lines of code intended for pulling and pushing a database
If you reach a point where you think "I don't actually have a facility for... downloading all the employees called smith" then you go to your dataset, you find the employees table adapter, you right click it and you Add Query.. SELECT * FROM employees WHERE name like #name, you call it FillByName, you finish the wizard, and suddenly your employeeTableAdapter has a new method called FillByName that takes a datatable and a string name. You call it like eta.FillByName(myXyzDataset.Employees, "Smith") - it does all the databasey bit for you, the command, the parameters, the connection..
You want to add a new employee; again it's dead easy and the tableadapter will save it, you just have to put the new emp into the local datatable:
Dim emp = myXyzDataSet.Employees.NewEmployeeRow()
emp.Name = "John Smith"
emp.Age = 23
...
myXyzDataSet.Employees.AddEmployeeRow(emp)
There's a shortcut if you know all the values:
myXyzDataSet.Employees.AddEmployeeRow("John Smith", 23, ...)
Either way your local data cache, the datatable, now contains a new record that needs saving. That's done with:
employeeTableAdapter.Update(myXyzDataSet.Employees)
The TA will look at the row and see it has been recently added. It will run the INSERT command it has built in - you don't need to do it
If you had edited a row:
Dim r = myXyzDataSet.Employees(0) 'first one.. or maybe you'll loop and find John Smith, or use the Find method..
r.Name = "Joe Smith"
Then the row knows it has been altered. The tableadapter will know it too, and when you call Update (think of it like Save, it's not just for SQL UPDATE) it will fire the built in UPDATE command and save the name change back to the DB.
Happens similarly for DELETE..
TableAdapters are the devices that pull and push data. If you want to add custom SQLs to your app, add them to the TAs and call the methods. Don't fill your code with direct use of db commands
I finally figured it out after another hour...
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
Dim Msg, Style, Title, Response, mystring
Msg = "Do you want to update employee ?"
Style = vbYesNo + vbCritical + vbDefaultButton2
Title = "MsgBox Demonstration"
' Display message.
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
DataGridView1.CurrentRow.Cells(0).Value = Me.ModEmpID.Text
DataGridView1.CurrentRow.Cells(1).Value = Me.ModLastName.Text
DataGridView1.CurrentRow.Cells(2).Value = Me.ModFirstName.Text
DataGridView1.CurrentRow.Cells(3).Value = Me.ModAddy.Text
DataGridView1.CurrentRow.Cells(4).Value = Me.ModSSN.Text
DataGridView1.CurrentRow.Cells(5).Value = Me.ModVehNum.Text
DataGridView1.CurrentRow.Cells(6).Value = Me.ModCerts.Text
For i As Integer = 0 To DataGridView1.Rows.Count - 1
Dim cmd4 As New SqlCommand("", con)
cmd4.CommandText = "update Employees set LastName ='" & DataGridView1.Rows(i).Cells(1).Value & "' , FirstName= '" & DataGridView1.Rows(i).Cells(2).Value & "' , AddressHalf = '" & DataGridView1.Rows(i).Cells(3).Value & "' , SSN = '" & DataGridView1.Rows(i).Cells(4).Value & "' , VehNumb = '" & DataGridView1.Rows(i).Cells(5).Value & "' , Certification = '" & DataGridView1.Rows(i).Cells(6).Value & "'Where EmpID = '" & DataGridView1.Rows(i).Cells(0).Value & "' "
con.Open()
cmd4.ExecuteNonQuery()
con.Close()
Next
MessageBox.Show("Employee Updated")
Else
mystring = True
MessageBox.Show("Cancelled")
End If
con.Close()
End Sub
I have an SQL table with 4 columns. The fourth column is FullName. I want this column to autofill itself from the results of 2nd and 3rd Column. ie.Firstname and Middlename.
I have tried this code
cn.Open()
Dim query As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', CONCATE(Textbox2.text, ',', Textbox3.Text))"
cmd = New SqlCommand(query, cn)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
The section CONCATINATE will be like the following:
"CONCATE('" & Textbox2.text &"',',','" & Textbox3.Text & "'))"
But i wont tell you to use like this, since it may a worst suggestion. I prefer you to use parameters as well to avoid injection and specifying the types.
Example:
Dim query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES (" & _
"#adm,#fName,#mName,CONCATE(#fNameC,',',#mNameC))"
Dim cmd As New SqlCommand(query, cn)
cmd.Parameters.Add("#adm", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#fName", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#mName", SqlDbType.VarChar).Value = TextBox3.Text
cmd.Parameters.Add("#fNameC", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#mNameC", SqlDbType.VarChar).Value = TextBox3.Text
'Execute the query here
Before query first store two textbox value in one variable
cn.Open()
Dim query As String
Dim fullname As String
fullname = TextBox1.text + "" + TextBox2.text
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & fullname & '")"
cmd = New SqlCommand(query, cn)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
You can concatenate with String.Concat, and I advice you to use the Parameter to avoid sql injections, like this :
cn.Open()
Dim query As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES (#Adm,#FirstName,#MiddleName,#FullName)"
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlParameter("#Adm", TextBox1.Text))
cmd.Parameters.Add(New SqlParameter("#FirstName", TextBox2.Text))
cmd.Parameters.Add(New SqlParameter("#MiddleName", TextBox3.Text))
cmd.Parameters.Add(New SqlParameter("#FullName", String.Concat(TextBox2.Text, ",", TextBox3.Text)))
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
Save the Firstname and Middlename values into variables and concat() them together before sending to the query.
cn.Open()
Dim query As String
Dim firstname As String
Dim middlename As String
Dim fullname As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName) VALUES (#Adm,#FirstName,#MiddleName,#FullName)"
firstname = TextBox2.Text
middlename = TextBox3.Text
fullname = String.Concat(firstname, ",", middlename)
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlParameter("#Adm", TextBox1.Text))
cmd.Parameters.Add(New SqlParameter("#FirstName", firstname))
cmd.Parameters.Add(New SqlParameter("#MiddleName",middlename))
cmd.Parameters.Add(New SqlParameter("#FullName", fullname))
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
Note that the query builder has been reformatted to remove vulnerability to SQL injection.
Use following line instead of your.
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & Textbox2.Text & " " & Textbox3.Text & "')"
I am new to vb.net and I am trying to insert a values from vb.net to msacess. I know alredy have a answer for this question here but those answers were not solving my problems so I post again
I am getting an error while inserting data into a database.
Ms-acess :
table name: reg
_________________
field |datatype
__________________
id |autonum
fname |text
lname |text
course|text
fees |number
amount|number
bal |number
The error is:
Number of query values and destination fields are not the same.
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "") Then
MessageBox.Show("Field Not Empty")
End If
connection = New OleDbConnection(ConfigurationManager.ConnectionStrings("DBConnect").ConnectionString)
connection.Open()
command = New OleDbCommand("insert into reg values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "'," + TextBox4.Text + "," + TextBox5.Text + "," + TextBox6.Text + ")", connection)
command.ExecuteNonQuery()
connection.Close()
MessageBox.Show("Data Added")
End Sub
Your SQL string must list the field names, probably:
"insert into reg (fname, lname, course, fees, amount, bal) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "'," + TextBox4.Text + "," + TextBox5.Text + "," + TextBox6.Text + ")"
Additional information: Syntax error (missing operator) in query expression ''1')'.
This is my code
Dim connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= Database1.mdb;")
Dim command As New OleDbCommand("INSERT INTO Student_Enquiry (StudentID,Email,Receiver,Comment) VALUES('" + TextBox3.Text + "','" + TextBox1.Text + "','" + ComboBox1.Text + "', '" + TextBox4.Text + "')", connection)
command.Connection.Open()
command.ExecuteNonQuery()
command.Connection.Close()
The issue is that the final closing parenthesis in the insert statement actually isn't a normal Right Parenthesis; it is a different character.
You used ) - "Fullwidth Right Parenthesis", U+FF09
instead of ) - "Right Parenthesis", U+0029, ASCII 0x29
Compare the the invalid and the valid: ) != )
Use this instead:
Dim command As New OleDbCommand("INSERT INTO Student_Enquiry (StudentID,Email,Receiver,Comment) VALUES('" + TextBox3.Text + "','" + TextBox1.Text + "','" + ComboBox1.Text + "', '" + TextBox4.Text + "')", connection)
Also, you really shouldn't inject values into the query but rather use parametrized queries to avoid issues with potential SQL injection etcetera. The documentation shows you how to do this.
i am getting this error in my coding can you please tell me what might be wrong? and how to rectify it
There is already an open DataReader associated with this Connection which must be closed first.
here in this sub i am retrieve data in the if part and in the else part i am inserting data. if a condition is not satisfied. so in the else part i am getting the above error
code is :
Dim con As MySql.Data.MySqlClient.MySqlConnection = New MySqlClient.MySqlConnection("server=localhost;user=root;database=zzz;port=3306;password;")
con.Open()
Dim cmd As MySqlClient.MySqlCommand
Dim dr As MySqlClient.MySqlDataReader
cmd = con.CreateCommand()
cmd.CommandText = "select sino FROM customers WHERE sino =('" + serialno.Text + "')"
cmd.ExecuteNonQuery()
dr = cmd.ExecuteReader()
If dr.HasRows = True Then
MsgBox("number already exists")
dr.Close()
ElseIf dr.HasRows = False Then
Dim sqlc As String
sqlc = "insert into customers values('" + serialno.Text + "','" + custname.Text + "','" + address.Text + "','" + phno.Text + "','" + eid.Text + "','" + event_type.Text + " ')"
Dim command As MySqlClient.MySqlCommand = New MySqlClient.MySqlCommand(sqlc, con)
command.ExecuteNonQuery()
MessageBox.Show(sqlc)
con.Close()
End If
A DataReader can only be associated with one open connection. When you are finished with the DataReader be sure you Close() it before reusing it again.
From MSDN:
http://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.80).aspx
1) Remove the cmd.ExecuteNonQuery(). The ExecuteReader immediately after is the only execute you need.
2) You have to use a different connection object for your insert command or close the previous reader. You can't reuse the same connection object while you are looping through a reader attached to it. So try this:
Dim con As MySql.Data.MySqlClient.MySqlConnection = New MySqlClient.MySqlConnection("server=localhost;user=root;database=zzz;port=3306;password;")
con.Open()
Dim cmd As MySqlClient.MySqlCommand
Dim dr As MySqlClient.MySqlDataReader
cmd = con.CreateCommand()
cmd.CommandText = "select sino FROM customers WHERE sino =('" + serialno.Text + "')"
dr = cmd.ExecuteReader()
If dr.Read = False Then
'we have no existing record
dr.Close() 'close reader first
Dim sqlc As String
sqlc = "insert into customers values('" + serialno.Text + "','" + custname.Text + "','" + address.Text + "','" + phno.Text + "','" + eid.Text + "','" + event_type.Text + " ')"
Dim command As MySqlClient.MySqlCommand = New MySqlClient.MySqlCommand(sqlc, con)
command.ExecuteNonQuery()
MessageBox.Show(sqlc)
con.Close()
Else
MsgBox("number already exists")
dr.Close()
End If
con.Close() 'close connection before leaving