MS-access INSERT INTO variables - ms-access

I have to make an audit trail that can keep track of the fields after INSERT INTO, however, I can't get any of the variables the expressions in "values" represents to go into the fields, only the expressions in VALUES. For instance, the two entries with numeric values give me numeric values, the others give me a string that is for instance Form.RecordSource = clientName
db.Execute "INSERT INTO tblAudit ([RecordID], [AuditWho], [AuditWhen], [AuditWhat], [AuditFrom], [AuditTo]) VALUES ('1', '2', 'Now()', 'Form.RecordSource = clientName' , ' Me.ClientName.Value ', ' Me.clientNameTextBox.Value ')"

At a minimum you need to do something like this:
Dim SQL as string
SQL = "INSERT INTO tblAudit ([RecordID], [AuditWho], [AuditWhen], [AuditWhat], [AuditFrom], [AuditTo]) VALUES ('1', '2','" & Now() & "', 'ClientName' , '" & Me.ClientName.Value & "', '" & Me.clientNameTextBox.Value & "')"
db.Execute SQL
To be more "robust" you should declare variables for AuditFrom and AuditTo values and validate that the data entered is "ok" before trying to perform the insert:
Dim SQL as string
dim strAuditFrom as string
Dim strAuditTo As String
strAuditFrom = Me.ClientName.Value & ""
strAuditTo = Me.ClientNameTextBox.Value & ""
if strAuditTo = vbNullString then
'Alert the user or throw an error perhaps?
end if
sql = "INSERT INTO tblAudit ([RecordID], [AuditWho], [AuditWhen], [AuditWhat], [AuditFrom], [AuditTo]) VALUES ('1', '2','" & Now() & "', 'ClientName' , '" &strAuditFrom & "', '" & strAuditTo & "')"
db.Execute sql

You're defining the text to insert by using the single qoutes. To get a value from a control and have it included in your query you need to escape the string using a double qoute, concatacate the string with the ampersand, find the value of the control, and continue the string with the ampsand and double qoute. For example:
db.Execute "INSERT INTO tblOne (Field1, Field2) VALUES ('literal text','" & ctlSomething & "')"

Related

ms-Access is removing leading zeros from a string

In the below code, the value of skuSet.Fields(0), which is a text field in the database, is "000000002".
If skuSet.RecordCount = 0 Then
sql = "SELECT Stock_Code FROM Stock WHERE Stock_Code = '" & stkLine.StockCode & "'"
Set skuSet = dbStock.OpenRecordset(sql, dbOpenDynaset)
End If
sql = "SELECT * FROM PickedByPicco WHERE OrderID = " & stkLine.OrderId & " AND StockCode = '" & skuSet.Fields(0) & "'"
Set SOPSLineSet = dbSOPS.OpenRecordset(sql, dbOpenDynaset)
If SOPSLineSet.RecordCount = 0 Then
sql = "INSERT INTO PickedByPicco(OrderID, StockCode, Qty, ScannedBy, ProcessedBy, processed) VALUES(" & stkLine.OrderId & _
", " & skuSet.Fields(0) & ", " & stkLine.Quantity & ", '" & stkLine.UserId & "', '', False)"
dbSOPS.Execute (sql)
When I step through the code, the value in skuSet.Fields(0) is still the same, as expected.
When the query has been executed, I check the PickedByPicco table, and the StockCode field shows just a value of 2 instead, and it's removed all of the leading 0's.
Why would it be doing this and how can I stop it?
That's because your INSERT statement looks like this:
INSERT INTO PickedByPicco (...) VALUES (..., 000000002, ...)
when it should look like this:
INSERT INTO PickedByPicco (...) VALUES (..., '000000002', ...)
(Note the quotes around your value.)
Normally, I'd tell you to use parameterized SQL, because SQL creation by string concatenation is evil, but, unfortunately, DAO's Database.Execute does not support that. So, the next best thing is to properly escape strings. To do that:
put single quotes around your value and
escape any single quotes occurring in your value:
I.e. this line
", " & skuSet.Fields(0) & ", " & ...
becomes
", '" & Replace(skuSet.Fields(0), "'", "''") & "', " & ...
While you are at it, be sure to replace single quotes in your other strings as well! Currently, a UserId of O'Brien would break your SQL, and other values might do worse.

Microsoft Access VBA INSERT SQL statement

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

Using Insert Command to Upsert to MySQL DB

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

Importing data from excel to mysql database using vba

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

Date format in Access insert into sql statement

Code below, but the date in the table is not showing correctly, my computer system date is set to yyyy,mm,dd and the Access table field is selected to short date. As seen in code below the date is showing fine when debugging and stepping through the program but at the end the date in the table is shown as 1905-12-30 (Which should be 2013-12-30) any suggestions please?
InsDate = Date
**InsDate** = Format(InsDate, "yyyy,mm,dd")
AppeQry = "INSERT INTO TStockMaster ( SupplierID, PartID, UnitsID, ConditionID, " & _
"QTY, WarehouseID, BinID, RowID, ColumnID, InsDate ) VALUES ( " & SupID & "," & PrtID & "," & UntID & "," & _
CondID & "," & Qt & "," & WarehID & "," & BnID & "," & RwID & "," & ColID & "," & **InsDate** & ");"
Use a parameter query instead of concatenating values as text into an INSERT statement.
Then, when you execute the statement, and supply the parameter value, you can give it the actual Date/Time value and not be bothered with text format and date type delimiters.
Here is a simplified example. Save this query as qryTStockMasterAppend.
INSERT INTO TStockMaster (InsDate) VALUES (pInsDate);
Then your VBA code can use that saved query, supply the parameter value and execute it.
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.QueryDefs("qryTStockMasterAppend")
qdf.Parameters("pInsDate") = Date()
qdf.Execute dbFailOnError