I can't seem to get my insert query to work in VB, it was working before and i tried to add a delete query and now the insert doesn't work.
I am searching for a customer in the customers table using their email (This works fine), the 3 fields from the customers table are then passed to another form where the user then adds more data to new fields, which are then used to insert into the members table. (I would also like to delete the customer from the customers table once they have been added to the members table using their email but can't seem to get it working).
This is the error I am getting 'Incorrect syntax near the keyword 'VALUES'.'
Here is the code for the insert query, any help would be appreciated. I am very new to Visual Basic.
This code is inside my SQLControl.vb
Public Sub Addmember(member_fname As String, member_sname As String, member_gender As String, member_dob As String,
member_address As String, member_postcode As String, member_email As String, member_contact_number As String,
member_registration As String, member_discount_rate As Integer)
Try
Dim strinsert As String = "INSERT INTO members (member_fname,member_sname,member_gender,member_dob,member_address,member_postcode,member_email,member_contact_number,member_registration,member_discount_rate " & _
"VALUES(" & _
"'" & member_fname & "'," & _
"'" & member_sname & "'," & _
"'" & member_gender & "'," & _
"'" & member_dob & "'," & _
"'" & member_address & "'," & _
"'" & member_postcode & "'," & _
"'" & member_email & "'," & _
"'" & member_contact_number & "'," & _
"'" & member_registration & "'," & _
"'" & member_discount_rate & "')"
MsgBox(strinsert)
SQLCon.Open()
SQLCmd = New SqlCommand(strinsert, SQLCon)
SQLCmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
And this is where the sub is being called on the button in the form
Private Sub addmember_Click(sender As Object, e As EventArgs) Handles addmember.Click
Try
sql.Addmember(memberupdate_firstname.Text, memberupdate_surname.Text, membergender.Text, memberdob.Text, memberaddress.Text, memberpostcode.Text, memberemail.Text, membercontactnumber.Text, memberregisterationdate.Text, membersdiscountrate.Text)
MsgBox("Member added")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You are missing a ) character between the end of the column list and the keyword values:
Dim strinsert As String = "INSERT INTO members (member_fname,member_sname,member_gender,member_dob,member_address,member_postcode,member_email,member_contact_number,member_registration,member_discount_rate " & _
")VALUES(" & _
"'" & member_fname & "'," & _
"'" & member_sname & "'," & _
"'" & member_gender & "'," & _
"'" & member_dob & "'," & _
"'" & member_address & "'," & _
"'" & member_postcode & "'," & _
"'" & member_email & "'," & _
"'" & member_contact_number & "'," & _
"'" & member_registration & "'," & _
"'" & member_discount_rate & "')"
Protect your code from Sql injection :
Public Sub Addmember(member_fname As String, member_sname As String, member_gender As String, member_dob As String,
member_address As String, member_postcode As String, member_email As String, member_contact_number As String,
member_registration As String, member_discount_rate As Integer)
Try
Dim queryInsert As String = "INSERT INTO members (member_fname,member_sname,member_gender,member_dob,member_address,member_postcode,member_email,member_contact_number,member_registration,member_discount_rate) " & _
" VALUES (#fname,#sname,#gender,#dob,#address,#postcode,#email,#contact_number,#registration,#discount_rate) "
Using sqlCon As New SqlConnection("MySqlConnectionString")
sqlCon.Open()
Using sqlCmd As New SqlCommand(queryInsert, sqlCon)
Dim fnameParam As SqlParameter = sqlCmd.Parameters.Add("#fname", SqlDbType.NVarChar, 10)
fnameParam.Value = member_fname
Dim snameParam As SqlParameter = sqlCmd.Parameters.Add("#sname", SqlDbType.NVarChar, 10)
snameParam.Value = member_sname
'etc. for all your parameters..
sqlCmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Related
pls help solve me this question.. im very new to this
i can't add new employee to the table employee.. whenever i try to add it shows syntax error insert into statement
Public Class AddNewEmployee
Dim dr As OleDbDataReader
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim conn As New OleDbConnection(My.Settings.rayshadatabaseConnectionString)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn.Open()
Try
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
cmd = New OleDbCommand(str, conn)
Dim i As Integer = cmd.ExecuteNonQuery()
If i > 0 Then
MessageBox.Show("Record Succesfully added.", "Process Completed", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Adding failed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Close()
cmd.Dispose()
End Try
frmEmployee.loadR()
Me.Close()
End Sub
End Class
Replace this,
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
with this,
Dim str As String = "INSERT INTO employee" _
& "([Employee Name], [IC Number], [HP Number], [Address])" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
Thanks
Manoj
I have this function in vb that had seemed to be working before to generate an 8 character password but now generates the same password for each user who registers to the website. I am unsure as to where I have went wrong as I have not fiddled with this piece of code (code was not written by me)? Any help would be appreciated.
function generatePassword()
Dim i, newPassword
newPassword = ""
For i = 1 to 3
newPassword = newPassword & Mid("ABCDEFGHJKLMNPQRSTUVWXYZ",randomInRange(1,24),1)
Next
For i = 4 to 7
newPassword = newPassword & Mid("23456789",randomInRange(1,8),1)
Next
'For i = 1 to 8
' newPassword = newPassword & Mid("ABCDEFGHJKLMNPQRSTUVWXYZ23456789",randomInRange(1,32),1)
'Next
generatePassword = newPassword
end function
function randomInRange(lo,hi)
randomInRange =(Int((hi - lo + 1) * rnd + lo))
end function
Dim newPassword = generatePassword()
Dim strSql As String = "INSERT INTO Student(" & _
"StudentNo," & _
"Surname," & _
"FirstName," & _
"MiddleName," & _
"Gender," & _
"Pathway," & _
"[Level]," & _
"QubEmail," & _
"[Password]," & _
"HomeEmail," & _
"MobilePhone," & _
"HomeTown," & _
"PlacementYear," & _
"Status," & _
"DateEdited," & _
"HomePhone) " & _
"VALUES " & _
"( " & _
"'" & StudentNo.Text.Replace("'", "''") & "'," & _
"'" & Surname.Text.Replace("'", "''") & "'," & _
"'" & Forename.Text.Replace("'", "''") & "'," & _
"'" & MiddleName.Text.Replace("'", "''") & "'," & _
"'" & ddlGender.SelectedValue & "'," & _
"'" & ddlPathway.SelectedValue & "'," & _
"'" & ddlLevel.SelectedValue & "'," & _
"'" & QUBEmail.Text.Replace("'", "''") & "'," & _
"'" & newPassword & "'," & _
"'" & HomeEmail.Text.Replace("'", "''") & "'," & _
"'" & MobileNo.Text.Replace("'", "''") & "'," & _
"'" & HomeTown.Text.Replace("'", "''") & "'," & _
"" & PlacementYear & "," & _
"'Seeking Placement'," & _
" GETDATE() ," & _
"'" & HomeNo.Text.Replace("'", "''") & "' " & _
")"
Dim addStudent As OleDbDataReader = Database.DoSQLReturnDataReader(strSql)
addStudent.Close()
There doesn't seem to be any code that is updating the rnd variable. This needs to update each time you call randomInRange to get different passwords.
I would suggest that you change randomInRange entirely to make it run more cleanly.
This is what you need to do:
Private rnd As Random = new Random()
Function randomInRange(lo As Integer, hi As Integer) As Integer
Return rnd.Next(lo, hi + 1)
End Function
Making this change produces random passwords.
You should probably talk to the person that wrote the code if you're not a programmer yourself. Nevertheless, a Rnd is really not random, but only a sofisticated mathematical equation using a seed to calculate its value.
This seed is set to the time when the program runs. Without any involvement, the seed will stay the same which means that all randoms will actually be the same value; use Randomize at each generatePassword().
Function generatePassword()
Randomize()
/.../
End Function
I'm running Visual studio and whenever I run my application it says "Incorrect syntax error near '(the email i enter appears here)'". I hope you can spot the mistake.
Within SQL server, my email column is called 'email'
Within Visual studio, the name of the input field for my email is called 'textEmail'
Public Sub AddCustomer(Firstname As String, Surname As String, Contactnum As String, Email As String)
Try
Dim strInsert As String = "INSERT INTO customers (firstname, surname, contactnum, email) " & _
"VALUES (" & _
"'" & Firstname & "'," & _
"'" & Surname & "'," & _
"'" & Contactnum & "'," & _
"'" & Email & "'"
MsgBox(strInsert)
SQLCon.Open()
SQLcmd = New SqlCommand(strInsert, SQLCon)
SQLcmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Code within form:
Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
'QUERY FOR CUSTOMER
SQL.RunQuery("SELECT * FROM customers WHERE customers.email = '" & txtEmail.Text & "' ")
If SQL.SQLDS.Tables(0).Rows.Count > 0 Then
MsgBox("This Email alredy exists!")
Exit Sub
Else
CreateCustomer()
End If
End Sub
Public Sub CreateCustomer()
' ADD CUSTOMER TO DATABASE
SQL.AddCustomer(txtFirst.Text, txtSur.Text, txtNum.Text, txtEmail.Text)
End Sub
End Class
Thanks for your time.
You are missing closing bracket
Dim strInsert As String = "INSERT INTO customers (firstname, surname, contactnum, email) " & _
"VALUES (" & _
"'" & Firstname & "'," & _
"'" & Surname & "'," & _
"'" & Contactnum & "'," & _
"'" & Email & "')"
When I try to edit and update the data in datagriview it comes up with an error message saying Operator '&' is not defined for type 'TextBox' and string "".
please help. Thanks
Here is my code
Private Sub btnaddrecord_Click(sender As Object, e As EventArgs) Handles btnaddrecord.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
If Me.IdentificationNotest.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO vehicledefects(Codenumber, vehiclereg, datereported, defects1, repaired1, defects2, repaired2, defects3, repaired3, datefixed) " & _
" VALUES(" & Me.IdentificationNotest.Text & ",'" & Me.vehiclereg.Text & "','" & Me.datereported.Text & "','" & Me.defects1.Text & "','" & Me.repaired1.Text & "','" & _
Me.defects2.Text & "','" & Me.repaired2.Text & "','" & _
Me.defects3.Text & "','" & Me.repaired3.Text & "','" & _
Me.datefixed.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE vehicledefects" & _
" SET Codenumber =" & Me.IdentificationNotest.Text & _
", vehiclereg ='" & Me.vehiclereg.Text & "'" & _
", datereported ='" & Me.datereported.Text & "'" & _
", defects1 ='" & Me.defects1.Text & "'" & _
", repaired1 ='" & Me.repaired1.Text & "'" & _
", defects2 ='" & Me.defects2.Text & "'" & _
", repaired2='" & Me.repaired2.Text & "'" & _
", defects3='" & Me.defects3.Text & "'" & _
", repaired3='" & Me.repaired3.Text & "'" & _
", datefixed='" & Me.datefixed.Text & "'" & _
" WHERE Codenumber =" & Me.IdentificationNotest.Tag
cmd.ExecuteNonQuery()
End If
refreshdata()
Me.btnclear.PerformClick()
cnn.Close()
datefixed.Text = ""
IdentificationNotest.Text = ""
End Sub
In the future, you should also post the line number the error is being thrown on.
The error is telling you that you're doing something like:
dim myString as String = myTextBox & " some more text"
in this case, you would need to do:
dim myString as String = myTextBox.Text & " some more text"
In the code you posted, I wasn't able to find an instance of this - so perhaps its somewhere else in the code. Though, the code was hard to read so I may have missed it.
You may also be aware that this code is susceptible to SQL Injection attacks
Ok, I have looked at a bazillion multi-threading examples; all show cute little counters on a form, while you can still access the form, using backgroundworker, or threadpools. I got it. What I don't get is to apply this into a real world application.
Here's my application, and I don't have a clue on how to multi-thread this;
Through a 3rd party ActiveX API I read in records to a SQL table at high rate; several million records in 8hours a day.
While the streaming of the records occurs, I need to go over the records, do some calculations and apply filters, and represent the results in realtime. (filters it down to around a 100 records/day)
I guess you see already where I'm going with this;
If I do the calculations/filters on the fly when records are streaming in; it causes the streaming to delay and I loose the connection, So I need to multi-thread the two tasks.
the streaming into SQL table is done as follows: (AxTDAAPIComm is the ActiveX)
On Form1 :
Private Sub SubscrBTN_Click(sender As Object, e As EventArgs) Handles SubscrBTN.Click
AxTDAAPIComm1.Subscribe(StreamOL, tdaactx.TxTDASubTypes.TDAPI_SUB_L1)
End Sub
Private Sub AxTDAAPIComm1_OnL1Quote(sender As Object, e As Axtdaactx.ITDAAPICommEvents_OnL1QuoteEvent) Handles AxTDAAPIComm1.OnL1Quote
SQL.AddStream(e.quote.Symbol, e.quote.Bid, e.quote.Ask, e.quote.Last, e.quote.PrevClose, e.quote.Volume, e.quote.TradeTime, e.quote.QuoteTime, e.quote.TradeDate, e.quote.QuoteDate, e.quote.Volatility, e.quote.OpenInterest, e.quote.UnderlyingSymbol, e.quote.CallPut, e.quote.LastSize, e.quote.MH_LastSize, e.quote.MH_IsQuote, e.quote.MH_IsTrade)
End Sub
End Class
clicking on the button, invokes the AxTDAAPIComm1_OnL1Quote sub, which streams back records.
Then in my SQL Class I send it off to my SQL table:
Public Sub AddStream(Symbol As String, Bid As Single, Ask As Single, Last As Single, PrevClose As Single, Volume As Integer, TradeTime As Integer, QuoteTime As Integer, TradeDate As Integer, Quotedate As Integer, Volatility As Single, OpenInterest As Integer, UnderlyingSymbol As String, CallPut As String, LastSize As Integer, MH_LastSize As Integer, MH_IsQuote As Boolean, MH_IsTrade As Boolean)
Try
Dim TradeAmount As Single = 0
Dim Trade As String = ""
TradeAmount = LastSize * Last * 100
Select Case Last
Case Is = Ask
Trade = "Ask"
Case Is > Ask
Trade = "Above Ask"
Case Is = Bid
Trade = "Bid"
Case Is < Bid
Trade = "Below Bid"
Case Else
Trade = "Mid"
End Select
Dim strStream As String = "INSERT INTO OptionStream (Symbol,Bid,Ask,Last,PrevClose,Volume,TradeTime,QuoteTime,TradeDate,QuoteDate,Volatility,OpenInterest,UnderlyingSymbol,CallPut,TradeAmount,Trade,LastSize,MH_LastSize,MH_IsQuote,MH_IsTrade) " & _
"VALUES (" & _
"'" & Symbol & "'," & _
"'" & Bid & "'," & _
"'" & Ask & "'," & _
"'" & Last & "'," & _
"'" & PrevClose & "'," & _
"'" & Volume & "'," & _
"'" & TradeTime & "'," & _
"'" & QuoteTime & "'," & _
"'" & TradeDate & "'," & _
"'" & Quotedate & "'," & _
"'" & Volatility & "'," & _
"'" & OpenInterest & "'," & _
"'" & UnderlyingSymbol & "'," & _
"'" & CallPut & "'," & _
"'" & TradeAmount & "'," & _
"'" & Trade & "'," & _
"'" & LastSize & "'," & _
"'" & MH_LastSize & "'," & _
"'" & MH_IsQuote & "'," & _
"'" & MH_IsTrade & "') "
SQLCon.Open()
SQLCmd = New SqlCommand(strStream, SQLCon)
SQLCmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
On my Form I have created a text box, which I use to enter a SQL query statement, which I capture as follows:
Private Sub cmdQuery_Click(sender As Object, e As EventArgs) Handles cmdQuery.Click
If txtQuery.Text <> "" Then
If SQL.HasConnection = True Then
SQL.RunQueryWL(txtQuery.Text)
If SQL.SQLDatasetWL.Tables.Count > 0 Then
DGVData.DataSource = SQL.SQLDatasetWL.Tables(0)
End If
End If
End If
End Sub
As you can see, it now goes of to the SQL class and runs the Query:
Public Function HasConnection() As Boolean
Try
SQLCon.Open()
SQLCon.Close()
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub RunQueryWL(Query As String)
Try
SQLCon.Open()
SQLCmd = New SqlCommand(Query, SQLCon)
SQLDA = New SqlDataAdapter(SQLCmd)
SQLDatasetWL = New DataSet
SQLDA.Fill(SQLDatasetWL)
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
If SQLCon.State = ConnectionState.Open Then
SQLCon.Close()
End If
End Try
End Sub
and the result is presented in a datagrid view on my form.
As you can imagine, querying against a couple million records takes a few seconds, therefore I want to put the AxTDAAPIComm1.Subscribe and AxTDAAPIComm1_OnL1Quote and the RunQueryWL Subs on different threads.
How do I do this?