vb.net multi-threading activex - vb.net

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?

Related

how to save (insert) data in datatable from datagridview in vb.net step by step

I am creating code for inserting data from datagridview in vb.net to database table Access 2007. But the program is for inserting data from user when he input data in datagridview in 1st row then after next time (after break by break) he input data again on 2nd , 3rd next row and click on save button in my project to insert data in database.
but problem arises when he click on save 2nd time for inserting data into database the process code insert all row old & new again. it is not proper inserting. it repeats data.
So please suggest me Solution
I am using dt for datatable and sql for sql statement.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim sql = "SELECT * FROM RABill "
maxrow = get_maxrow(sql)
For i = 0 To DgRAbill.Rows.Count - 2
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM RABill ")
Dim strInsert As String = "INSERT INTO RABill (Billnumber,RDate,RAmount,Below,Royalti,SD,IT,GSTminus,RAccountname,GstTwelvepercent,Insurance,Other,TotalBill,Remark) VALUES ('" _
& CStr(DgRAbill.Rows(i).Cells(1).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(2).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(3).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(4).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(5).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(6).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(7).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(8).FormattedValue) & "','" _
& ComboBox1.Text & "','" _
& CStr(DgRAbill.Rows(i).Cells(10).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(11).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(12).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(13).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(14).FormattedValue) & "')"
cmd = New OleDbCommand(strInsert, conn)
cmd.ExecuteNonQuery()
MsgBox("Record Saved Successfully")
Next
End Sub
in above code my datagridview has extra row in it so it code is rows-2
You don't appear to be clearing the variable 'strInsert' after the insert so this may be the issue you are facing?
I would be tempted to clear the variable after the MsgBox.
Many Thanks
POC
There are a couple of concerning things with your code snippet here.
Is your database suppose to be able to have duplicate entries? You might want to look at how your primary keys are set up.
You should really have some error catching in here, especially with database connections. Take a look through this for reference : https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/try-catch-finally-statement
As for the actual double entry - you're not clearing out your datagridview after saving all the records. If I'm understanding correctly the user fills in a bunch of rows in the DGV then hits save and it loops through and inserts them all. Then he continues entering and hits save again and it inserts all of them (some duplicates). After saving you should do a .Clear on your DGV - or you need to create some kind of counter that persists between saves and that's where you'll start your for loop at in the save button Below is clearing it after each save:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim sql = "SELECT * FROM RABill "
maxrow = get_maxrow(sql)
For i = 0 To DgRAbill.Rows.Count - 2
Try
Dim strInsert As String = "INSERT INTO RABill (Billnumber,RDate,RAmount,Below,Royalti,SD,IT,GSTminus,RAccountname,GstTwelvepercent,Insurance,Other,TotalBill,Remark) VALUES ('" _
& CStr(DgRAbill.Rows(i).Cells(1).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(2).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(3).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(4).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(5).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(6).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(7).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(8).FormattedValue) & "','" _
& ComboBox1.Text & "','" _
& CStr(DgRAbill.Rows(i).Cells(10).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(11).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(12).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(13).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(14).FormattedValue) & "')"
cmd = New OleDbCommand(strInsert, conn)
cmd.ExecuteNonQuery()
MsgBox("Record Saved Successfully")
DgRabill.Rows.Clear()
Catch ex As Exception
MessageBox.Show("Error Inserting record at row " & i & vbCrLf & ex.Message)
End Try
Next
End Sub
You can use following code to bind and save your DataGridView data to your database.
Dim connString As String = ""
Private ds As DataSet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ds = New DataSet()
Using con As SqlConnection = New SqlConnection(connString)
con.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter("select * from RABill", con)
adp.Fill(ds)
Dim dt As DataTable = ds.Tables(0)
DataGridView1.DataSource = dt
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using con As SqlConnection = New SqlConnection(connString)
con.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter("select * from RABill", con)
Dim build As SqlCommandBuilder = New SqlCommandBuilder(adp)
adp.Update(ds.Tables(0))
End Using
End Sub
Whatever you edit in your DataGridView, click button1 those records will be saved in the database.

syntax error insert into statement vb.net

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

insert and delete query in visual studio

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

Incorrect syntax error near 'email'

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 & "')"

The CommandText property has not been properly initialized

i am using vb.net and mysqladmin as my database.
i have a problem in my codes, and i don't know how to debug it.
please help me..
my problem is when i click the button update the error shows
"The CommandText property has not been properly initialized."
this is the codes:
Dim intDB_ID_Selected As Integer
'Private Sub cmdupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdupdate.Click
If MessageBox.Show("Do you want to update this record?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then
Dim sqlcommand As New MySqlCommand("UPDATE user_info " & _
" SET name = '" & txtname.Text.Trim & "'," & _
" address = '" & txtaddress.Text.Trim & "', " & _
" age = '" & txtage.Text.Trim & "', " & _
" WHERE id= '" & intDB_ID_Selected & "'", sConnection)
Call execCmd(SQL)
load1()
MsgBox("Record updated successfully.", MsgBoxStyle.Information)
End If
End Sub `
Public Sub execCmd(ByVal PstrSQL As String)
With cmd
.CommandText = PstrSQL
.ExecuteNonQuery()
End With
End Sub
the error line is in
.ExecuteNonQuery()
i am a beginner in this language, so please help me. im begging you guys!!
what is cmd and has it been initialized?
Oh, and try to used parameterized query. The earlier you get into the habit, the better.
Try doing this instead after the messagebox selection. cmd is not properly initialized in execCmd.
Dim sqlStr as String = "UPDATE user_info " & _
" SET name = '" & txtname.Text.Trim & "'," & _
" address = '" & txtaddress.Text.Trim & "', " & _
" age = '" & txtage.Text.Trim & "', " & _
" WHERE id= '" & intDB_ID_Selected & "'", sConnection)
Dim sqlcommand As New MySqlCommand(sqlStr)
sqlcommand.ExecuteNonQuery()
load1()
MsgBox("Record updated successfully.", MsgBoxStyle.Information)