Formatting Field In Dao Database - Access VBA - vba

I have this code for a DAO - Database
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim sqlinsert As String
sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Number]) Values ('" & rs("[Number]") & "') "
DoCmd.RunSQL (sqlinsert)
When I run this, the Number will often be to a large decimal place, implying the need for Round(,2) or Format(, " #.00").
However, this code does not function.
sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Number]) Values ('" & rs("Format([Number], "#.00")") & "') "
Any ideas as to what the code should be?

sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Number]) Values ('" & Format(rs("[Number]"), "#.00") & "') "

Related

Insert Date into MS Access vba Query

I'm trying to insert the current date into a table using VBA in MS Acess. The date gets inserted as 12/30/1899 No matter what I try. Any advise to fix this? Here is my code
Dim StrSQL As String
Dim db As Database
Dim InID As Integer
Dim Inputcasedate As String
Dim InputCaseType_Id As Integer
InID = Me.PgmPart_ID
Inputcasedate = Date
InputCaseType_Id = 1
StrSQL = "INSERT INTO CaseNotes (PgmPart_ID,CaseType_ID,CaseDate) " & _
"VALUES (" & InID & "," & InputCaseType_Id & "," & Inputcasedate & ")"
In MS Access, literal date values must be delimited by pound/numeral/hashtag symbols: #.
StrSQL = "INSERT INTO CaseNotes (PgmPart_ID,CaseType_ID,CaseDate) " & _
"VALUES (" & InID & ", " & InputCaseType_Id & ", #" & Inputcasedate & "#)"
However, like VBA, Access SQL maintains the Date() function. So use this expression inside the SQL statement and avoid the concatenated VBA variable.
StrSQL = "INSERT INTO CaseNotes (PgmPart_ID,CaseType_ID,CaseDate) " & _
"VALUES (" & InID & ", " & InputCaseType_Id & ", Date())"
However, consider the industry best practice with parameterized SQL which MS Access's DAO supports via QueryDefs.Parameters. Doing so, requires no value delimiters like quotes for strings or numerals for dates and aligns data types between app layer (VBA) and database.
Dim StrSQL As String
Dim db As Database
Dim qdef As QueryDef
' PREPARED STATEMENT (NO VBA VARIABLES)
StrSQL = "PARAMETERS ParamInID Long, ParamInputCaseType_Id Long; " & _
"INSERT INTO CaseNotes (PgmPart_ID, CaseType_ID, CaseDate) " & _
"VALUES (ParamInID, ParamInputCaseType_Id, Date());"
' INITIALIZE DAO OBJECTS
Set db = CurrentDb
qdef = db.CreateQueryDef("", StrSQL)
' BIND PARAMETERS
qdef!ParamInID = Me.PgmPart_ID
qdef!ParamInputCaseType_Id = 1
' EXECUTE ACTION
qdef.Execute
Set qdef = Nothing: Set db = Nothing

SQL query from VB.Net to Access database

I have a query but when I try it's giving me some error on a date or any other variable. I can't get it right. Can you please help me? Here is the code:
Dim tax As Integer = 10
Dim APPROVED As Boolean = 1
Dim admin As String = "admin"
sqlquery.CommandText = "INSERT INTO ACCOUNTS (REFERENCE_NO, ACCT_DATE, ACCT_FROM, ACCT_DUE_DATE, TOTAL, [CURRENCY], AMOUNTS_ARE, TAX, APPROVED, UPDATED_BY, UPDATED_DATE) VALUES ('" & TextBox2.Text & "', #" & DateTimePicker1.Value.Date & "#, '" & TextBox1.Text & "', #" & DateTimePicker2.Value.Date & "#, " & TextBox3.Text & ", '" & ComboBox1.SelectedItem.ToString & "', '" & ComboBox2.SelectedItem.ToString & "', " & tax & ", '" & APPROVED & "', '" & admin & "', #" & DateTimePicker1.Value.Date & "#);"
sqlquery.ExecuteNonQuery()
Now I am getting this error:
Data type mismatch in criteria expression.
Which date format want to follow?
Use parameterized queries.
What you have is crazy vulnerable to sql injection attacks. Parameterized queries will fix that issue and your formatting issue:
Dim tax As Integer = 10
Dim APPROVED As Boolean = 1
Dim admin As String = "admin"
sqlquery.CommandText = "INSERT INTO ACCOUNTS (REFERENCE_NO, ACCT_DATE, ACCT_FROM, ACCT_DUE_DATE, TOTAL, [CURRENCY], AMOUNTS_ARE, TAX, APPROVED, UPDATED_BY, UPDATED_DATE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
sqlquery.Parameters.Add("?", OleDbType.VarWChar, 10).Value = TextBox2.Text
sqlquery.Parameters.Add("?", OleDbType.Date).Value = DateTimePicker1.Value.Date
'...
sqlquery.ExecuteNonQuery()
Data type mismatch in criteria expression. You are trying to insert the wrong data-type into your database. Double check your data types in your database. If its a date, insert a date, if it's text, insert text.
Further more, string concatenation make it harder to find errors and it also leaves your open to SQL injection.
Here is a simple example of using parameters:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = " & My.Settings.dbpath
con.Open()
Dim sql_insert As String = "INSERT INTO Table_Name (Order_ID, Customer_Name) " & _
"VALUES " & _
"(#entry_ref, #customer_name);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("#entry_ref", entry_ref)
.Parameters.AddWithValue("#customer_name", tb_new_entry_customer_name.Text.Trim())
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.close()
End Using
As you can see, it's easy to follow and protects your database at the same time.

Insert into statement with an apostophe using VBA?

I have a form with textboxes. I am inserting what the user enters into the textbox into a table. If the user enters an apostrophe in the textbox labeled "Me.ProjectName", I get an error. My code is:
CurrentDb.Execute "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Me.ProjectName & "')"
You should not construct and execute dynamic SQL based on user input. You should use a parameterized query, something like:
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim qdf As DAO.QueryDef
Set qdf = cdb.CreateQueryDef("", _
"INSERT INTO Table1 (ProjectNumber, Title) VALUES (#prjnum, #title)")
qdf.Parameters("#prjnum").Value = ProjectNumber
qdf.Parameters("#title").Value = me.ProjectName
qdf.Execute
You should escape your strings possibly containing quotes by replacing a quote with 2 quotes:
Dim SQL As String
SQL = "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Replace(Me.ProjectName, "'", "''") & "')"
CurrentDb.Execute SQL

MS Access runtime error 3464

I am working on a database for my work and i'm trying to insert and update values from tables with sql inside the vb editor
This is my code:
Option Compare Database
Private Sub Übernehmen_Click()
Dim strSQL1 As String
Dim strSQL2 As String
Dim strSQL3 As String
Dim ArtikelNr As Integer
Dim Stück As Integer
Dim Lieferant As String
Dim Bestellnr As Integer
Dim EkPreis As String
Dim Mwst As String
Dim Einkaufsort As String
Dim GhIndex As String
Dim Datum As String
Dim Uhrzeit As String
Dim Lager As String
Dim Beschreibung As String
ArtikelNr = [Forms]![Einkauf]![ArtikelNr].Value
Stück = [Forms]![Einkauf]![Stück].Value
Lieferant = [Forms]![Einkauf]![Lieferant].Value
Bestellnr = [Forms]![Einkauf]![Bestellnr].Value
EkPreis = [Forms]![Einkauf]![EK-Preis].Value
Mwst = [Forms]![Einkauf]![Mwst-Satz].Value
Einkaufsort = [Forms]![Einkauf]![Einkaufsort].Value
GhIndex = [Forms]![Einkauf]![GH-Index].Value
Datum = [Forms]![Einkauf]![Datum].Value
Uhrzeit = [Forms]![Einkauf]![Uhrzeit].Value
Lager = [Forms]![Einkauf]![Lager].Value
strSQL1 = "INSERT INTO Einkäufe (ArtikelNr, Stück, Lieferant, Bestellnr, EKPreis, MwstSatz, Einkaufsort, GHIndex) VALUES (" & ArtikelNr & "," & Stück & ",'" & Lieferant & "','" & Bestellnr & "','" & EkPreis & "','" & Mwst & "','" & Einkaufsort & "','" & GhIndex & "');"
Beschreibung = DLast("EinkaufID", "Einkäufe")
strSQL2 = "INSERT INTO Transaktionen VALUES ('" & ArtikelNr & "','" & Datum & "','" & Lager & "','" & Stück & "','EinkaufID ' + '" & Beschreibung & "' ,'Einkauf',NULL,NULL,'" & Uhrzeit & "');"
strSQL3 = "UPDATE Lagerbestand SET Stück = Stück+" & Stück & " WHERE ArtikelNr = '" & ArtikelNr & "' AND Lager = '" & Lager & "';"
DoCmd.RunSQL strSQL1
DoCmd.RunSQL strSQL2
DoCmd.RunSQL strSQL3
End Sub
After trying to press the button it first adds the two entries and stops at the third one just to throw an error saying "Runtime Error: 3464".
After I press debug it marks the line DoCmd.RunSQL strSQL3.
I would appreciate any answer I get.
Many thanks in advance.
A quick google of "Runtime Error 3464" suggests this is a data type mismatch. You'll typically see this when you try to save a date value in a string field or something like that.
Double check the types passed to your SQL statements match the columns they should be saved to - and apply any necessary conversions if you spot differences.
Also one final heads up...by building your SQL string dynamically you are leaving yourself vulnerable to SQL Injection attacks - you should consider using ADOCommands with parameters.
My error was trying to compare an integer with a string. Even though sql does cast it from an integer to a string if you make a new entry, it does not cast it if you want to compare in a where.

SQL Insert into statement

strSQL = "INSERT INTO Accounts UserName, Password VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
When the code is executed and error is thrown, but there is no visible problem that i can see. Help!
The word PASSWORD is reserved in MS-Access.
You need to use square brackets around that name (Or change it to something different)
strSQL = "INSERT INTO Accounts (UserName, [Password]) VALUES (......
Said that, please use a parameterized query to build sql commands.
A string concatenation like yours is easily attacked by hackers using SQL Injection
Also, if the username or password contains a single quote, the resulting sql text built using string concatenation will be invalid.
strSQL = "INSERT INTO Accounts (UserName, [Password]) VALUES (?, ?)"
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
cmd.Parameters.AddWithValue("#p1",txtUsername.Text);
cmd.Parameters.AddWithValue("#p2",txtEncryptedPassword);
cmd.ExecuteNonQuery();
You forgot parentheses:
strSQL = "INSERT INTO Accounts (UserName, Password) VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
try this code:
Dim strSQL As String = "INSERT INTO tblDetail VALUES('" & strPersonCode _
& "','" & strForename & "','" & strSurname & "','" & strDateOfBirth & "'," & strCurrentlyWith & ",'" & strConditions & "')"
Do it like that but change to your names.
Declare the values of text boxes as strings and just use those.
your doing () this mistake and you should must add:
your code:
strSQL = "INSERT INTO Accounts UserName, Password VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
you should must change code following as:
strSQL = "INSERT INTO Accounts (UserName, Password) VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
update1:
"INSERT INTO `test`.`users` ( `username`, `password`) " & _
"VALUES ('" & txtUsername.Text & "', '" & txtPassword.Text & "');"
update2:
"INSERT INTO users ( `username`,`password`)VALUES(#txtUsername.Text,#txtPassword.Text);"
"INSERT INTO users (Username,Password)VALUES(?,?);"
note:test means database name you should change your databasename.