good day, i have the following codes:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim cmd As New OleDb.OleDbCommand
Dim compDate As Date
Dim x As New Integer
Dim profID As New Integer
Dim date1 As New Date
compDate = Format(Date.Now, "hh:mm:ss, tt")
'MsgBox(compDate)
date1 = #8:00:00 AM#
profID = 201400001
x = 1
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
'Timer1.Start()
Timer1.Interval = 5000
sp.Close()
Try
sp.Open()
Catch
sp.Close()
End Try
If TextBox1.Text = "201400001" Then
If DateDiff(DateInterval.Minute, date1, Date.Now) > 5 Then
MsgBox("been here")
cmd.CommandText = "UPDATE test " & _
"SET ProfLog" & x & "" & _
"WHERE ProfID='" & Me.TextBox1.Text & "' AND ProfTime=#" & date1 & "#"
cmd.ExecuteNonQuery()
MsgBox("Did this")
End If
MsgBox("Done!")
ElseIf TextBox1.Text = "201400002" Then
MsgBox("Hello World Again!")
ElseIf TextBox1.Text = "201400003" Then
MsgBox("My Turn!")
End If
TextBox1.Clear()
End Sub
once it reach the cmd.ExecuteNonQuery, a syntax error is being displayed. it says that there is a "Syntax error in UPDATE statement" i would like to know what is the syntax that makes my program go wrong. Thanks in advance.
You have an error in your UPDATE statement. You're missing an = after SET ProfLog:
"UPDATE test " & _
"SET ProfLog = " & x & "" & _
"WHERE ProfID='" & Me.TextBox1.Text & "' AND ProfTime=#" & date1 & "#"
You could have figured this out yourself by showing the cmd.CommandText in a message box or the immediate window in Visual Studio.
Please do yourself a huge favor and search for "parameterized queries" or "SQL injection". You should learn to do things properly from the start, instead of learning to do them poorly and causing yourself many, many problems later.
Related
I have 2 datatable with these fields
*dataordner
Archive Date/Time (datetimepicker, it's already data)
Storage Short Text (combobox)
BulanOrdner ShortText (combobox)
TahunOrdner Date/Time (datetimepicker)
*datalemari
Archive Date/Time (datetimepicker, it's already data)
Storage Short Text (combobox)
Lemari Short Text (combobox)
BulanOrdner ShortText (combobox)
TahunOrdner Date/Time (datetimepicker)
and now I am very confused why i'm wrong
What I have tried:
I've done with my codes but always error with that error "no value given for one more...."
I call 2 table with if else in combobox(storage)
These are my code sequences, i think that's all true with selected item in combobox
note:
storage = combobox
Private Sub storage_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles storage.SelectedIndexChanged
If storage.SelectedIndex = 1 Then
groupordner.Visible = True
grouplemari.Visible = False
Else
If storage.SelectedIndex = 2 Then
groupordner.Visible = False
grouplemari.Visible = True
End If
End If
End Sub
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
If storage.SelectedItem = "Ordner" Then
str = "Update dataordner set Storage = " & storage.Text & ", BulanOrdner = " & bulanordner.Text & ", TahunOrdner = '" & tahunordner.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
proses.ExecuteNonQuery(str)
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
Else
If storage.SelectedItem = "Lemari" Then
str = "Update datalemari set Storage = " & storage.Text & ", Lemari = " & lemari.Text & ", BulanLemari = " & bulanlemari.Text & ", TahunLemari = '" & tahunlemari.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
proses.ExecuteNonQuery(str)
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
End If
End If
End Sub
There might me some control's value that is null or Nothing, you can use Debugging with Breakpoints to check null values Or there might be Objects that are not initialized.
You can also try the code below :
Note : I will recommend you to use Parameterized Query instead
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
If storage.SelectedItem Is Nothing Then
MsgBox("Plese Select the item first", MsgBoxStyle.Exclamation)
Else
If conn.State <> ConnectionState.Open Then
conn.Open() '' Assuming conn is your OleDbConnection
End If
Dim cmd As OleDbCommand = conn.CreateCommand
Try
If storage.SelectedItem = "Ordner" Then
Str = "Update dataordner set Storage = " & storage.Text & ", BulanOrdner = " & bulanordner.Text & ", TahunOrdner = '" & tahunordner.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
cmd.CommandText = Str
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
Else
If storage.SelectedItem = "Lemari" Then
Str = "Update datalemari set Storage = " & storage.Text & ", Lemari = " & lemari.Text & ", BulanLemari = " & bulanlemari.Text & ", TahunLemari = '" & tahunlemari.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
cmd.CommandText = Str
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
End If
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
Finally
conn.Close()
End Try
End If
End Sub
I have been trying to display selected data from Access database into datagridview on pressing the button but its not displaying any records neither it is showing any error.
Dim third_da As OleDb.OleDbDataAdapter
Dim third_ds As New DataSet
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
con.Open()
Dim cb_two As New OleDb.OleDbCommandBuilder(third_da)
query_three = "SELECT emp_timing.emp_code, emp_timing.day, emp_timing.travel_time, emp_timing.travel_dest,emp_timing.emp_timein,emp_timing.emp_timeout, emp_timing.emp_hours, emp_timing.emp_mins " & _
"FROM emp_timing WHERE (((emp_timing.emp_code)=" & empcode & ") AND ((emp_timing.day) Like '??/" & ComboBox1.Text & "/20" & TextBox9.Text & "'))"
' "WHERE (((emp_timing.emp_code)=22) AND ((emp_timing.day) Like '??/05/2016'))"
third_da = New OleDb.OleDbDataAdapter(query_three, con)
third_da.Fill(third_ds, "ets")
DataGridView1.DataSource = third_ds.Tables("ets")
con.Close()
Dim view As New DataView(third_ds.Tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
DataGridView1.ReadOnly = True
DataGridView1.CancelEdit()
End Sub
Thanks in Advance!
You can change you condition of emp_timing.day field in query like this :
(Month(emp_timing.day) = & ComboBox1.Text &
and Year(emp_timing.day) = "20" & TextBox9.Text & " )
But, I advice you to use the Parameter to avoid SQL injections , like this :
query_three = "SELECT emp_timing.emp_code, emp_timing.day, emp_timing.travel_time, emp_timing.travel_dest,emp_timing.emp_timein,emp_timing.emp_timeout, emp_timing.emp_hours, emp_timing.emp_mins " &
"FROM emp_timing WHERE (((emp_timing.emp_code)= #empcode) AND ((emp_timing.day) BETWEEN #startDate AND #endDate ))"
Dim startDate As New DateTime("20" & TextBox9.Text, ComboBox1.Text, 1)
Dim endDate As DateTime = startDate.AddMonths(1).AddDays(-1)
Dim cmd As New OleDbCommand(query_three, con)
cmd.Parameters.AddWithValue("#empcode", empcode)
cmd.Parameters.AddWithValue("#startDate", startDate.ToString("#yyyy/MM/dd#"))
cmd.Parameters.AddWithValue("#endDate", endDate.ToString("#yyyy/MM/dd#"))
third_da = New OleDb.OleDbDataAdapter(cmd)
I've got an app that checks every few seconds for new orders.
If it sees a new entry in the database, it fires off a BackgroundWorker to process it.
I have 3 list boxes on my form, pending, completed and failed.
Theres is a second BackgroundWorker process which asynchronously checks with an api to see if the order has been fully processed yet, before moving the item in question to the 'completed' list box.
Everything seems to be working fine until I throw a few orders at a time at the app.
It processes the orders fine and adds them to pending, and it will check back on a few of them but eventually get stuck in the secondbackground worker process.
It will eventually crash out with a "This BackgroundWorker is currently busy" error.
I've gone over my code lots of times and I can't see where it would be crashing out.
Whats the best way for me to diagnose this?
Heres the code for the background worker where I'm getting stuck...
Private Sub BuildProgressCheck_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) _
Handles BuildProgressCheck.DoWork
lblstatus.Text = "Checking back on async jobs"
Dim i As Integer
For i = 0 To buildpendinglist.Items.Count - 1
Beep()
Dim cn As New MySqlConnection
cn.ConnectionString = "server=" & dbserver & "; userid=" & dbusername & "; password=" & dbpassword & "; database=" & dbdatabase & ";Convert Zero Datetime=True"
Dim jobcheck As New MySqlDataAdapter("Select * FROM dbcpman_jobs WHERE dbxid='" & buildpendinglist.Items(i) & "'", cn)
Dim jobcheck_table As New DataTable
jobcheck.Fill(jobcheck_table)
Dim jobrow As DataRow
jobrow = jobcheck_table.Select("failed = 'false'").FirstOrDefault()
If Not jobrow Is Nothing Then
Dim job_id As String = jobrow.Item("id")
Dim job_jobid As String = jobrow.Item("jobid")
Dim job_status As String = jobrow.Item("status")
Dim job_dbxid As String = jobrow.Item("dbxid")
Dim jobcommand As String = "command=queryAsyncJobResult&jobId=" & job_jobid
Dim fulljobapicheckurl = cpapiurl & jobcommand
Try
Dim jobapicall As New System.Net.WebClient
jobcheckresult = jobapicall.DownloadString(fulljobapicheckurl)
Catch ex As Exception
''Problem submitting the api request?
End Try
If jobcheckresult.Contains("<jobstatus>1</jobstatus>") Then ''If true, job has completed
Dim doc As New System.Xml.XmlDocument
doc.LoadXml(jobcheckresult) ''api_result contains xml returned from a http request.
If doc.GetElementsByTagName("virtualmachine") IsNot Nothing Then
Dim elem As XmlNodeList = doc.GetElementsByTagName("virtualmachine").Item(0).ChildNodes
For Each item As XmlNode In elem
If item.Name.Equals("state") Then
new_vm_state += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("hostname") Then
new_vm_hostname += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("templatename") Then
new_vm_templatename += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("cpunumber") Then
new_vm_cpunumber += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("cpuspeed") Then
new_vm_cpuspeed += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("memory") Then
new_vm_memory += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("nic") Then
new_vm_netmask += ((item.ChildNodes.Item(3).InnerText.ToString()) + Environment.NewLine)
new_vm_gateway += ((item.ChildNodes.Item(4).InnerText.ToString()) + Environment.NewLine)
new_vm_ipaddress += ((item.ChildNodes.Item(5).InnerText.ToString()) + Environment.NewLine)
new_vm_macaddress += ((item.ChildNodes.Item(11).InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("instancename") Then
new_vm_instancename1 += ((item.InnerText.ToString()) + Environment.NewLine)
End If
Next
End If
new_vm_macaddress = new_vm_macaddress.ToUpper
Dim privateip As String = new_vm_ipaddress.Replace(" ", "").ToString
Dim publicip As String = privateip.Replace("172.16.11.", "198.73.112.")
Try
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "DELETE FROM dbcpman_jobs WHERE jobid = '" & job_jobid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "UPDATE dbcpman_vm SET deployresponse = '" & jobcheckresult & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "UPDATE dbcpman_vm SET macaddress = '" & new_vm_macaddress & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "UPDATE dbcpman_vm SET publicip = '" & publicip & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "UPDATE dbcpman_vm SET privateip = '" & privateip & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
Dim new_vm_username As String = "clouduser"
Dim new_vm_password As String = GeneratePassword(7)
System.Threading.Thread.Sleep(1000)
Dim new_vm_support_username As String = "dbxsupport"
Dim new_vm_support_password As String = GenerateSupportPassword(7)
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "INSERT into dbcpman_credentials(username1, username2, password1, password2, type, link) VALUES ('" & new_vm_username & "','" & new_vm_support_username & "','" & new_vm_password & "','" & new_vm_support_password & "','Server root logon','" & job_dbxid & "')"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "INSERT into dbcpman_vm_boot(dbxid, ip, macaddress, hostname) VALUES ('" & job_dbxid & "','" & new_vm_ipaddress & "','" & new_vm_macaddress & "','" & job_dbxid & "')"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
Try ''''add monitoring for this new host
Dim monitorurl As String = "http://192.168.16.32/addhost.php?hostname=" & job_dbxid & "&ipaddr=" & publicip
Dim webClient As New System.Net.WebClient
Dim monresult As String = webClient.DownloadString(monitorurl)
If monresult = "SUCCESS" Then
''success message
Else
''fail message
End If
Catch ex As Exception
End Try
buildcompletedlist.Items.Add(buildpendinglist.Items(i))
buildpendinglist.Items.Remove(buildpendinglist.Items(i))
buildprogresscheckactive = 0
BuildProgressCheck.CancelAsync()
Catch ex As Exception
End Try
ElseIf jobcheckresult.Contains("<jobstatus>0</jobstatus>") Then ''If true, job is still pending
''job still pending - do nothing, will check again on next pass
ElseIf jobcheckresult.Contains("<jobstatus>2</jobstatus>") Then ''If true, job has failed
Try
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "UPDATE dbcpman_jobs SET failed = 'true' WHERE jobid = '" & job_jobid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
buildfailedlist.Items.Add(buildpendinglist.Items(i))
buildpendinglist.Items.Remove(buildpendinglist.Items(i))
Catch ex As Exception
BuildProgressCheck.CancelAsync()
buildprogresscheckactive = 0
End Try
End If
End If
Next
buildprogresscheckactive = 0
End Sub
My best guess based on the appended text and code is as follows:
"..checks every few seconds for new orders."
Error: "This BackgroundWorker is currently busy"
So I believe you're starting the asynchronous work in a Tick event of a Timer. So, let's say your timer ticks every 2 seconds.
Friend WithEvents mytimer As New System.Windows.Forms.Timer With {.Interval = 2000, .Enabled = True}
Private Sub _Tick(sender As Object, e As EventArgs) Handles mytimer.tick
Me.BuildProgressCheck.RunWorkerAsync()
End Sub
Now, lets imagine that for 6 ticks BuildProgressCheck_DoWork are executed in less than 2 seconds. No error occurs and everything seems okay. But, at the 7th tick it take 3 seconds. Then, when the timer raise tick for the 8th time, the BackGroundWorker is "currently busy" and throws an error.
What you need to do is to suspend the timer before running the worker and resume it when the worker has completed. Here's an example:
Private Sub _Tick(sender As Object, e As EventArgs) Handles mytimer.Tick
'Suspend the timer:
Me.mytimer.Enabled = False
'Do background work:
Me.BuildProgressCheck.RunWorkerAsync()
End Sub
Private Sub _DoWork(sender As Object, e As DoWorkEventArgs) Handles BuildProgressCheck.DoWork
'Important: Do not invoke any UI controls inside this method.
' (We're inside the background thread)
End Sub
Private Sub _ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BuildProgressCheck.ProgressChanged
'Here you can safely invoke UI controls.
'(We're inside UI thread)
'Me.Label1.Text = "Started..."
End Sub
Private Sub _RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BuildProgressCheck.RunWorkerCompleted
Try
If (e.Error Is Nothing) Then
If (e.Cancelled) Then
'Cancelled
Else
'Success
End If
Else
'Error
End If
Catch ex As Exception
'...
Finally
'Restart the timer.
Me.mytimer.Enabled = True
End Try
End Sub
i want Insert datetime from datagridview to database.But i'm don't save required.
Ex.
Datagridview
DAte
2012-11-20 16:36:39
when i'm save to datagridview to datebase
DAte
1900-01-01 00:00:00.000
I want save 2012-11-20 16:36:39 to dataasbe but it's don't result.
Show Datagridview
Dim sqlSentMaterial As String = ""
Dim DT_SentMaterial As New DataTable
sqlSentMaterial = "SELECT rc.No,rc.ReceiveDate as RCReceiveDate,rc.CreateBy as RCReceiveBy,rc.CreateDate,rc.ReceiveNote "
sqlSentMaterial &= "FROM RClother rc "
sqlSentMaterial &= "Where rc.No ='" & Search & "'"
DT_SentMaterial = FShowData(sqlSentMaterial)
For i As Integer = 0 To DT_SentMaterial.Rows.Count - 1
If DT_SentMaterial.Rows.Count <> 0 Then
Dim item As New DataGridViewRow
item.CreateCells(DgvSentMaterial)
With item
.Cells(1).Value = TxtBarcode.Text
If DT_SentMaterial.Rows(0).Item("RCReceiveDate") Is DBNull.Value Then
.Cells(2).Value = ""
Else
.Cells(2).Value = CDate(DT_SentMaterial.Rows(0).Item("RCReceiveDate")).ToString("dd/MM/yyyy")
End If
End With
DgvSentMaterial.Rows.Add(item)
Exit For
End If
Next
Form save datagridview to database
Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
Dim sentMat As Integer
sentMat = FInsertSentMatClother(CInt(DgvSentMaterial.Rows(i).Cells(1).Value), CDate(DgvSentMaterial.Rows(i).Cells(2).Value))
End Sub
Function Insert To Database
Public Function FInsert_iPOSentMatClother(ByVal BarCode As Integer, ByVal RCReceiveDate As Date)
Dim Tr As SqlTransaction
Dim sqlCom As New SqlCommand
Dim sqlInsert As String
Dim ReturnValue As Integer
Dim GetDate As DateTime = DateTime.Now
Try
Tr = Conn.BeginTransaction
sqlCom.Connection = Conn
sqlInsert = "INSERT INTO SentMatClother "
sqlInsert &= "(BarCode,ReceiveDate) "
sqlInsert &= "VALUES('" & BarCode & "','" & RCReceiveDate & "')"
sqlCom.Transaction = Tr
sqlCom.CommandText = sqlInsert
sqlCom.CommandType = CommandType.Text
ReturnValue = CInt(sqlCom.ExecuteScalar) 'CInt(sqlCom.ExecuteScalar)
If ReturnValue = 0 Then
Tr.Commit()
Else
Tr.Rollback()
End If
Catch ex As Exception
'MsgBox(ex.ToString)
Finally
If Not sqlCom Is Nothing Then
sqlCom.Dispose()
End If
sqlCom = Nothing
End Try
Return ReturnValue
End Function
Thanks you for you time. :)
in your Function insert to database just format Date value in string as you want
sqlInsert = "INSERT INTO SentMatClother "
sqlInsert &= "(BarCode,ReceiveDate) "
sqlInsert &= "VALUES('" & BarCode & "','" & RCReceiveDate.ToString("yyyy-MM-dd HH:mm:ss") & "')"
or and on my opinion is a better practice using a parameters:
sqlInsert = "INSERT INTO SentMatClother (BarCode,ReceiveDate) VALUES (#barCode, #receiveDate)"
//then add parameters to your sqlCommand
sqlCom.Parameters.AddWithValue("#barCode", BarCode)
sqlCom.Parameters.AddWithValue("#barCode", RCReceiveDate)
I have a problem sending data to my access database.
I get this error
NullReferenceExeption was Unhandled - "Object reference not set to an instance of an object."on this part of my codemaxrows = ds.Tables("asdf").Rows.Count
What would that mean?
Here is my code :
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
ID = TextID.Text
FName = Textfname.Text
LName = Textlname.Text
If con.State = ConnectionState.Closed Then
con.Open()
End If
If TextID.Tag & "" = "" Then
cmd = New OleDbCommand("INSERT INTO asdf(ID,fname,lname) " & _
"VALUES(' " & TextID.Text & "', '" & Textfname.Text & "', '" & Textlname.Text & "')", con)
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE asdf" & _
"SET ID=" & TextID.Text & _
", fname='" & Textfname.Text & "'" & _
",lname ='" & Textlname.Text & "'" & _
", WHERE ID =" & TextID.Tag
End If
btnClear.PerformClick()
MessageBox.Show("Data successfully saved!")
maxrows = ds.Tables("asdf").Rows.Count ' <---- Exception occurs here
inc = 1
con.Close()
RefreshData()
End Sub
Put a break-point (F9 or click in the margin) on this line of code: maxrows = ds.Tables("asdf").Rows.Count and run it.
Take these steps:
Hover over ds or right-click and select Quick Watch and see if it
says null.
If it doesn't, highlight ds.Tables("asdf") and Quick Watch it and
see if it's null.
If not, then highlight ds.Tables("asdf").Rows and see if that's
null.
One of these has to be null if it's crashing there. If that's the case, then you didn't fill it correctly or there wasn't nothing to fill it with.