SQL = "UPDATE `tblitems` SET `itemsOnHand` = `itemsOnHand` - '" & PartnumItemsNumericUpDown.Value & "' WHERE `itemID` = '" & itemIDTextBoxX.Text & "' ;"
SQL = "UPDATE `tblitems` SET `itemsOnHand` = `itemsOnHand` + '" & PartnumItemsNumericUpDown.Value & "' WHERE `itemID` = '" & itemIDTextBoxX.Text & "' ;"
--- Just want to ask why the first sub function sql command (-) works but (+) wont...please help. itemsOnHand is integer type.
Please DO NOT concatenate strings to build sql command text. ALWAYS use Parameters it avoid sql injection. Parameter values are not executable code but a simple concatenation can hold "Delete * From tblitems."
I had to guess at the datatypes for the parameters.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ItemId As Integer
If Not Integer.TryParse(itemIDTextBoxX.Text, ItemId) Then
MessageBox.Show("Please enter a number in Item Id.")
Return
End If
Dim Sql = "UPDATE `tblitems` SET `itemsOnHand` = `itemsOnHand` - #PartNumber WHERE `itemID` = #ItemID"
Using con As New MySqlConnection(ConStr),
cmd As New MySqlCommand(Sql, con)
cmd.Parameters.Add("#PartNumber", MySqlDbType.Int32).Value = PartnumItemsNumericUpDown.Value
cmd.Parameters.Add("#ItemID", MySqlDbType.Int32).Value = ItemID
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
You are much less likely to run into problems with + and - using parameters since you don't need all the single quotes and double quotes.
The minus sign was interpreted as an arithmetic operator and the plus sign was interpreted as a concatenation character.
Related
I have created a database within Microsoft access and with it a form.
I have a button attached to the form and when it's clicked I want to insert a new record into the table customerHeader.
There are four fields within that table one being an autonumber. In my SQL statement, I don't include the orderNumber since it is an autofield.
When I try to click the button and the on click event is executed, I get an error saying that Microsoft Access cannot append the records in the append query.
Any ideas, I have looked everywhere and I have not been able to find the solution.
Private Sub addOrder_Click()
Dim mySql As String
Dim rowNum As Integer
Dim recCount As Long
Dim orderNumber As Long
Dim myBool As Boolean
Dim todayDate As Date
todayDate = CDate(Date)
myBool = False
MsgBox todayDate
rowNum = Form.CurrentRecord
rowNum = CInt(rowNum - 1)
'DoCmd.GoToRecord , , acNewRec
mySql = "INSERT INTO orderHeader (orderDate,custNumber,printed) VALUES (" & todayDate & "," & rowNum & "," & myBool & ")"
DoCmd.RunSQL mySql
Me!orderNum.Requery
You don't have to much around - just use the ISO sequence for the format of the string expression for the date value:
mySql = "INSERT INTO orderHeader (orderDate,custNumber,printed) VALUES (#" & Format(todayDate, "yyyy\/mm\/dd") & "#," & rowNum & "," & myBool & ")"
However, it it's today, simply use:
mySql = "INSERT INTO orderHeader (orderDate,custNumber,printed) VALUES (Date()," & rowNum & "," & myBool & ")"
Please help me. I added a delete method in the check printing system that i'm creating, before it was working well, but when I changed the data type of the field Check_Number from text to number from their respective tables, it is no longer deleting the data row that i select. i do not remember changing any code from the delete section. do u guys have any idea how to solve this? thank you in advance. More power!
The different Bank_[BankName] has the ff fields and data types:
ID - AutoNumber
Check_Number - Number
Company_ID - Text
My VN_ZAM table has the ff fields and datatypes:
ID - AutoNumber
Voucher_Number - Number
Check_Number - Text
Bank_Type - Text
Company_ID - Text
My SS table has the ff fields and datatypes (this is also where the data in the datagrid view is taken from):
ID - AutoNumber
Check_No - Text
Voucher_No - Text
Issue_Date - Date/Time
Company_Name - Text
Bank_Type - Text
Amount_in_Figure - Number
Amount_in_Words - Text
Payee - Text
My datagridview order looks like this:
ID | Check_No | Voucher_No | Issue_Date | Company_Name |Bank_Type | Amount_in_Figure | Amount_in_Words | Payee
.
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim sql As String
Dim sql1 As String
Dim sql2 As String
Dim answer As Integer
answer = MsgBox("Are you sure you want to delete this record?", vbYesNo + vbDefaultButton1, "Information")
'If answer = vbYes Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Pc\Documents\Visual Studio 2010\Projects\bankCheckSystem\dbcheckprintsystem.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
sql = "DELETE * FROM SS WHERE ID =" & dgvSSCheckRecords.SelectedRows(0).Cells(0).Value.ToString()
If dgvSSCheckRecords.SelectedRows(0).Cells(12).Value.ToString() = "ZAM" Then
sql1 = "DELETE * FROM VN_ZAM WHERE Company_ID = '" & dgvSSCheckRecords.SelectedRows(0).Cells(4).Value.ToString() & "_" & dgvSSCheckRecords.SelectedRows(0).Cells(0).Value.ToString() & "' "
Dim cmd As OleDbCommand = New OleDbCommand(sql, myConnection)
Dim cmd1 As OleDbCommand = New OleDbCommand(sql1, myConnection)
'cmd.ExecuteNonQuery()
'cmd1.ExecuteNonQuery()
If dgvSSCheckRecords.SelectedRows(0).Cells(5).Value.ToString() = "BDO" Then
sql2 = "DELETE * FROM Bank_BDO WHERE Company_ID = '" & dgvSSCheckRecords.SelectedRows(0).Cells(4).Value.ToString() & "_" & dgvSSCheckRecords.SelectedRows(0).Cells(0).Value.ToString() & "' AND Check_Number ='" & dgvSSCheckRecords.SelectedRows(0).Cells(1).Value.ToString() & "'"
Dim cmd2 As OleDbCommand = New OleDbCommand(sql2, myConnection)
cmd.ExecuteNonQuery()
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
ElseIf dgvSSCheckRecords.SelectedRows(0).Cells(5).Value.ToString() = "BPI" Then
sql2 = "DELETE * FROM Bank_BPI WHERE Company_ID = '" & dgvSSCheckRecords.SelectedRows(0).Cells(4).Value.ToString() & "_" & dgvSSCheckRecords.SelectedRows(0).Cells(0).Value.ToString() & "' AND Check_Number ='" & dgvSSCheckRecords.SelectedRows(0).Cells(1).Value.ToString() & "'"
Dim cmd2 As OleDbCommand = New OleDbCommand(sql2, myConnection)
cmd.ExecuteNonQuery()
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
End if
End Sub
As Strawberry alludes to, I can't find any examples of DELETE * FROM being valid syntax (I'm not sure you can use it like SELECT * FROM ?). Also if the Check_Number in the Bank tables has changed to number, I'm not sure you need the single quotes around the values. Does it help if you change your four SQL statements to the following?
sql = "DELETE FROM SS WHERE ID = " & dgvSSCheckRecords.SelectedRows(0).Cells(0).Value.ToString()
sql1 = "DELETE FROM VN_ZAM WHERE Company_ID = '" & dgvSSCheckRecords.SelectedRows(0).Cells(4).Value.ToString() & "_" & dgvSSCheckRecords.SelectedRows(0).Cells(0).Value.ToString() & "' "
sql2 = "DELETE FROM Bank_BDO WHERE Company_ID = '" & dgvSSCheckRecords.SelectedRows(0).Cells(4).Value.ToString() & "_" & dgvSSCheckRecords.SelectedRows(0).Cells(0).Value.ToString() & "' AND Check_Number = " & dgvSSCheckRecords.SelectedRows(0).Cells(1).Value.ToString()
sql2 = "DELETE FROM Bank_BPI WHERE Company_ID = '" & dgvSSCheckRecords.SelectedRows(0).Cells(4).Value.ToString() & "_" & dgvSSCheckRecords.SelectedRows(0).Cells(0).Value.ToString() & "' AND Check_Number = " & dgvSSCheckRecords.SelectedRows(0).Cells(1).Value.ToString()
I'm creating an update Sub class in VB and use the insert instead of Update in Query because i want to update a multiple data in one run.
this is my references in multiple update data: SQL - Update multiple records in one query
but when I run it there is an error message.
"Missing semicolon (;) at end of SQL statement."
but in the end of my Query there is a Semicolon.
Here is my Query:
Insert into IngredientStock(IngredientID,CategoryId,UnitID,IngredientName,Price)
values(46,2,1,'Beans', 100) ON DUPLICATE KEY
UPDATE
ingredientID= Values(IngredientID),
CategoryID = Values(CategoryID),
UnitID = Values(UnitID),
IngredientName = Values(IngredientName),
Price = values(Price);
Here is my update Sub class
Sub UpdateInfo(ByVal table As String, ByVal PrimaryKey As String, ByVal C1 As String, ByVal C2 As String, ByVal C3 As String, ByVal C4 As String, ByVal Datas As String)
con.Close()
con.Open()
Query = "Insert into " & table & "(" & PrimaryKey & "," & C1 & "," & C2 & "," & C3 & "," & C4 & ") values (" & Datas & ") ON DUPLICATE KEY UPDATE " & PrimaryKey & "= Values(" & PrimaryKey & "), " & C1 & " = values(" & C1 & ")," & C2 & " = values(" & C2 & "), " & C3 & " = values(" & C3 & ")," & C4 & " = values(" & C4 & ");"
cmd = New OleDbCommand(Query, con)
DR = cmd.ExecuteScalar
con.Close()
End Sub
First, never ever concat strings to create a SQL query. If something like the ingredient contains special characters (e.g. Palmer's Condensed Milk) it will fail.
SQL Parameters also preserve the data type - according to the one snippet, only one item is string, but the code is forcing them all to text. Additionally (and most importantly) SQL Parameters avoid SQL injection.
You need something like this for a MySQL Upsert:
Dim sql = <sql>
INSERT INTO SampleZ
(Id, Name, Country, Animal, Color, Price, ItemDate, Active)
VALUES
(#id, #n, #c, #a, #clr, #p, #dt, #act)
ON DUPLICATE KEY UPDATE
Name=#n, Country=#c,
Animal=#a, Color=#clr, Price=#p,
ItemDate=#dt, Active=#act
WHERE id = #id
</sql>.Value
Using dbcon As New MySqlConnection(connStr)
Using cmd As New MySqlCommand(sql, dbcon)
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = thisID
If thisID = -1 Then
cmd.Parameters("#id").Value = DBNull.Value
End If
cmd.Parameters.Add("#n", MySqlDbType.String).Value = TextBox1.Text
cmd.Parameters.Add("#c", MySqlDbType.String).Value = ComboBox1.Text
cmd.Parameters.Add("#a", MySqlDbType.String).Value = TextBox2.Text
cmd.Parameters.Add("#clr", MySqlDbType.String).Value = TextBox3.Text
cmd.Parameters.Add("#p", MySqlDbType.Decimal).Value = NumericUpDown1.Value
cmd.Parameters.Add("#dt", MySqlDbType.DateTime).Value = DateTimePicker1.Value
cmd.Parameters.Add("#act", MySqlDbType.Bit).Value = chkActive.Checked
dbcon.Open()
Dim rows = cmd.ExecuteNonQuery()
End Using
End Using
Important Notes:
The above uses an XML literal so the query can be formatted to make sense
Each value is a Parameter with the datatype specified (MySqlDbType.DateTime
The Using blocks assure that the DbCOnnection and DbCommand object are properly closed and disposed at the end so the app doesnt leak resources
The UPDATE portion gets the data by assigning the same parameters.
MySql ON DUPLICATE KEY UPDATE Syntax
ingredientID= Values () <-- here
values clause is not required.
Liink --> On Duplicate Key Update same as insert
Please I badly needed your help. I have the following code that returns a table from ms access displayed in a data grid view based on the user's input. But when I tried to run it, I have encountered the error "Syntax error (comma) in query expression 'lastname = '' , firstname = '' , midname = '''." Please someone help me
here is my code.
Dim sql As String = "SELECT `lastname` as 'FAMILY NAME',`firstname` as 'NAME', `midname` AS 'MIDDLE NAME', `sex` as 'SEX', `birthdate` as 'BIRTHDAY', `Address` as 'ADDRESS', `barangay` AS 'BARANGAY', `patientID` AS 'PID' FROM `tblinformation_offline` WHERE lastname = '" & TextBox1.Text & "' , firstname = '" & TextBox3.Text & "' , midname = '" & TextBox4.Text & "' "
Dim cn As New OleDbConnection(constring)
cn.Open()
Dim da As New OleDbDataAdapter(sql, cn)
Dim ds As New DataSet
da.Fill(ds, "AccessData")
cn.Close()
With Me.DataGridView1
.DataSource = ds
.DataMember = "AccessData"
End With
ds = Nothing
da.Dispose()
cn = Nothing
First problem, a WHERE clause is a one or more conditions linked together by a logical operator like AND or OR. Your WHERE list a series of values and this is not a valid syntax
.... FROM `tblinformation_offline`
WHERE lastname = 'xxxxx'
AND firstname = 'yyyyyy'
AND midname = 'zzzzz"
This will fix your immediate error.
As you can see I have removed the string concatenation to let you see more clearly your errors, but now there is the problem of your use of string concatenation to build sql queries. Don't do it but use a parameterized query
In a parameterized query you use the Parameters collection of the MySqlCommand to pass your values, while the string that contains the text is filled with parameter's placeholders
Dim sql As String = "SELECT ...... FROM `tblinformation_offline` " & _
"WHERE lastname = #lname AND firstname = #fname AND midname = #mname"
Using cn As New OleDbConnection(constring)
Using da As New OleDbDataAdapter(sql, cn)
da.SelectCommand.Parameters.Add("#lname", MySqlDbType.VarChar).Value = TextBox1.Text
da.SelectCommand.Parameters.Add("#fname", MySqlDbType.VarChar).Value = TextBox3.Text
da.SelectCommand.Parameters.Add("#mname", MySqlDbType.VarChar).Value = TextBox4.Text
Dim ds As New DataSet
da.Fill(ds, "AccessData")
cn.Close()
With Me.DataGridView1
.DataSource = ds
.DataMember = "AccessData"
End With
ds = Nothing
End Using
End Using
Finally in the query text used there are errors. When you write
"SELECT `lastname` as 'FAMILY NAME' ....
You are creating records where the value of the column lastname is filled with the string "FAMILY NAME" because you use the single quote character instead of the backticks as you do around the columns (the same applies to the other columns as well)
I´m trying to import data into a MySQL Database, i have searched for many examples and solutions but it didn´t working and i have no idea why. Below is my vba code. I am getting runtime error 2147217900(80040e14) saying that you have an error in your sql syntax; chek the manual that corrsponds to your mysqlfor the right syntax to use near '='41282'
Sub Getdata()
Dim conn As New ADODB.Connection
Dim server_name As String
Dim database_name As String
Dim user_id As String
Dim password As String
Dim a As Long ' counter
Dim i As Long, j As Variant, k As Long
Dim sqlstr As String ' SQL to perform various actions
Dim table1 As String, table2 As String
Dim field1 As String, field2 As String
Dim field3 As String
Dim rs As ADODB.Recordset
sqlstr = "INSERT INTO" & table1 & "SET" _
& field1 & " = '" & i & "', " _
& field2 & " = '" & j & "', " _
& field3 & " = '" & k & "'"
conn.Execute sqlstr
Next a
End With
skipwrite:
End Sub
Simply, space out the table name and SET command in the concatenated string. Also, add tick marks before and after due to the reserved words used in column names (which by the way should be avoided as best practices):
sqlstr = "INSERT INTO " & table1 & " SET " _
& "`" & field1 & "` = '" & Format(i, "YYYY-MM-DD") & "', " _
& "`" & field2 & "` = '" & j & "', " _
& "`" & field3 & "` = '" & k & "';"
Also as mentioned by #Lelio, format the date to read properly into a MySQL Date column.
Date in Excel are stored as number of days between 1899-12-31 and the actual date. What you are trying to do is to store a number in a field that has a numeric format.
41282 is the number of days. So you should calculate something like:
'1899-12-31' + 'i days'
to get the date in mysql format (that by default is YYYY-MM-DD). I don't know the exact string manipulation command for VBA to get this but on the MYSQL side this should fix your error