Insert Into Statement VBA [closed] - ms-access

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi everyone I am coding in VBA using Access 2013 I wrote my code two different ways and keep getting a syntax error. Here's my code.
Private Sub cmdAdd_Click()
CurrentDb.Execute "INSERT INTO GroupVolunteers(Group, Leader, Name,
phone, email, EmergencyContact, EmergencyContact) " & _
" VALUES(" & Me.txtGroup & "','" & Me.cboLeader & "','" & Me.txtName & "','"
& Me.txtEmail & "','" & Me.txtPhone & "','" & Me.txtEmergencyContact & "','"
& Me.EmergencyNumber & "','" & Me.txtRegNumber & "')"
'clear form
cmdClear_Click
'refresh data in list on form
frmStudentSub.Form.Requery
End Sub
OR
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtRegNumber & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO GroupVolunteers(Group, Leader, Name,
phone, email, EmergencyContact, EmergencyContact) " & _
" VALUES(" & Me.txtGroup & "','" & Me.cboLeader & "','" &
Me.txtName & "','" & _
Me.txtEmail & "','" & Me.txtPhone & "','" &
Me.txtEmergencyContact & "','" & Me.EmergencyNumber & "','" &_
Me.txtRegNumber & "')"
Else
'otherwise (Tag of txtID store the id of student to be modified)
CurrentDb.Execute "UPDATE GroupVolunteers " & _
" SET Group=" & Me.txtGroup & _
", leader='" & Me.cboLeader & "'" & _
", name='" & Me.txtName & "'" & _
", email='" & Me.txtEmail & "'" & _
", phone='" & Me.txtPhone & "'" & _
", EmergencyContact='" & Me.txtEmergencyContact & "'" & _
", EmergencyNumber='" & Me.txtEmergencyNumber & "'" & _
", NumberVolunteers ='" & Me.txtNumberVolunteers & "'" & _
" WHERE RegNumber = " & Me.txtRegNumber.Tag

" VALUES(" & Me.txtGroup & "', ...
Think of how that's going to end up in your statement:
VALUES(<Me.txtGroup>', ...
In other words, you're either missing the opening quote for a character-type column or you have too many for a numeric-type column. It should be one of:
" VALUES('" & Me.txtGroup & "', ... // for character-type column
" VALUES(" & Me.txtGroup & ", ... // for numeric-type column
That should fix your insert in both code blocks, you may also want to examine the update in the second code block as well. It has no quotes on the group column which is okay if it's numeric-type but probably not if it's character-type.

Related

Visual Basic Access - recording information from Textboxes

I'm trying to create a form that allows you to register users. I've looked up tutorials and none of them seem to work. This is the code I am stuck with currently:
CurrentDb.Execute "INSERT INTO tblUser(User ID, Fullname, Username, Password, Security) " _
& VALUES & " (" & Me.ID & ",'" & Me.Fullname & "','" & Me.Uname & "','" & _
Me.uPass & "','" & Me.Pri & "')"
When I run the code I get:
Runtime error '3134': Syntax error in INSERT INTO statement.
Two errors:
You have space in one of your field. Use brackets if you have space
or if you use reserved words.
VALUES must be included in the string, not as a varible.
Correction:
CurrentDb.Execute "INSERT INTO tblUser([User ID], Fullname, Username, Password, Security) " & _
"VALUES (" & Me.ID & ",'" & Me.Fullname & "','" & Me.Uname & "','" & _
Me.uPass & "','" & Me.Pri & "')"
From my comment, try below:
CurrentDb.Execute "INSERT INTO tblUser(User ID, Fullname, Username, Password, Security) " _
& "VALUES(" & Me.ID & ",'" & Me.Fullname & "','" & Me.Uname & "','" & _
Me.uPass & "','" & Me.Pri & "')"
Password is a reserved word, so:
CurrentDb.Execute "INSERT INTO tblUser(User ID, Fullname, Username, [Password], Security) " _

Update subform after information is added

So here's my problem I can get my subform to requery once but that is it I can't get it to requery after new information is entered. Can someone please help! I have tried using RecordsetClone and that didn't work as well as other suggestions and I haven't been able to get anything to work
Private Sub cmdAdd_Click()
CurrentDb.Execute "INSERT INTO tbl_GroupVolunteers (GroupName, Leader,
VolunteerName, Email, Phone, EmergencyContact, EmergencyNumber,
NumberofVolunteers, RegistrationNumber)" & _
"VALUES ('" & Me.txtGroupName & "','" & Me.cboLeader & "','" &
Me.txtVolunteerName & "','" & Me.txtEmail & "','" & Me.txtPhone & "','" &
Me.txtEmergencyContact & _
"','" & Me.txtEmergencyNumber & "','" & Me.txtNumberofVolunteers & "','" &
Me.txtRegistrationNumber & "')"
'refresh data
Me!subformGroupVolunteers.Form.Requery
'Clear form
cmdClear_Click
End Sub
Put a break in your code and step through it to see where it's failing. I'd suggest separating the Execute function. Something like this:
Dim sqlStr as String
sqlStr = "INSERT INTO tbl_GroupVolunteers (GroupName, Leader,
VolunteerName, Email, Phone, EmergencyContact, EmergencyNumber,
NumberofVolunteers, RegistrationNumber)" & _
"VALUES ('" & Me.txtGroupName & "','" & Me.cboLeader & "','" &
Me.txtVolunteerName & "','" & Me.txtEmail & "','" & Me.txtPhone & "','" &
Me.txtEmergencyContact & _
"','" & Me.txtEmergencyNumber & "','" & Me.txtNumberofVolunteers & "','" &
Me.txtRegistrationNumber & "')"
CurrentDb.Execute sqlStr
'refresh data
Me!subformGroupVolunteers.Form.Requery
'Clear form
cmdClear_Click
Or instead of stepping through it, you can add a messagebox like this:
Dim sqlStr as String
sqlStr = "INSERT INTO tbl_GroupVolunteers (GroupName, Leader,
VolunteerName, Email, Phone, EmergencyContact, EmergencyNumber,
NumberofVolunteers, RegistrationNumber)" & _
"VALUES ('" & Me.txtGroupName & "','" & Me.cboLeader & "','" &
Me.txtVolunteerName & "','" & Me.txtEmail & "','" & Me.txtPhone & "','" &
Me.txtEmergencyContact & _
"','" & Me.txtEmergencyNumber & "','" & Me.txtNumberofVolunteers & "','" &
Me.txtRegistrationNumber & "')"
Msgbox sqlStr 'Display the string
CurrentDb.Execute sqlStr
'refresh data
Me!subformGroupVolunteers.Form.Requery
'Clear form
cmdClear_Click
This way, you can step through the variable and make sure the string that gets created is functioning properly. If records aren't being added correctly, then it's probably because that INSERT INTO statement isn't pulling in the data properly.

Run-time error '3061': Too Few Parameters. Expected 2

So I'm trying to teach myself VBA again and I'm having a cople of troubles. I'm trying to add new users to a table but keep getting the above error when I click my "Update" button. The text field will be in the form of 2 letters and 5 numbers. XX11111 for example.
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtLoginName.Tag & "" = "" Then
'add data to table
CurrentDb.Execute "INSERT INTO tblUsers(LoginName,UserName,Rank) " & _
" VALUES('" & Me.txtLoginName & "','" & Me.txtUsername & "','" & Me.cboRank & "')"
Else
CurrentDb.Execute "UPDATE tblUsers " & _
"set LoginName=" & Me.txtLoginName & "'" & _
", UserName='" & Me.txtUsername & "'" & _
", Rank='" & Me.cboRank & "'" & _
" WHERE LoginName=" & Me.txtLoginName.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
frmModifyUsersSub.Form.Requery
End Sub
you are missing a ' in this line:
" set LoginName=" & Me.txtLoginName & "'" & _
change it to
" set LoginName='" & Me.txtLoginName & "'" & _
and :
" WHERE LoginName=" & Me.txtLoginName.Tag
to
" WHERE (LoginName='" & Me.txtLoginName.Tag & "')" ' and I don't know if this your intended where condition.
The error pretty much gives you the answer. You need 2 parameters for the function it is failing on. One thing to try is to change
CurrentDb.Execute "INSERT INTO tblUsers(LoginName,UserName,Rank) " & _
" VALUES('" & Me.txtLoginName & "','" & Me.txtUsername & "','" & Me.cboRank & "')"
and
CurrentDb.Execute "UPDATE tblUsers " & _
"set LoginName=" & Me.txtLoginName & "'" & _
", UserName='" & Me.txtUsername & "'" & _
", Rank='" & Me.cboRank & "'" & _
" WHERE LoginName=" & Me.txtLoginName.Tag
To
CurrentDb.Execute "INSERT INTO tblUsers(LoginName,UserName,Rank) " & _
" VALUES('" & Me.txtLoginName & "','" & Me.txtUsername & "','" & Me.cboRank & "')",dbFailOnError
and
CurrentDb.Execute "UPDATE tblUsers " & _
"set LoginName='" & Me.txtLoginName & "'" & _
", UserName='" & Me.txtUsername & "'" & _
", Rank='" & Me.cboRank & "'" & _
" WHERE LoginName='" & Me.txtLoginName.Tag & "'", dbFailOnError

Runtime Error 3061 VBA using Insert command

I have the following code. I am using a form in MS Access 2010 to enter new lines into my table Nlog. When I try to run the code, it gives me the error Run-Time error '3061': Too few parameters. Expected 1.
I can't find the error!
Private Sub Command128_Click()
'add data to table
CurrentDb.Execute "INSERT INTO NLog(IDKEY, Company, CoName, State, City, AmtpdTotal, DateRec, Notified, DateNotice, AcctID, TaxType, Period, NoticeReason, Resolution, TaxDue, Intdue, PenDue, Dateres, Amtpdint, amtpdpen, amtpdtax, Assigned, subAssgn, Resolved) " & _
" VALUES(" & Me.TxtIDKEY & ",'" & Me.Company & "','" & Me.CoName & "','" & _
Me.State & "','" & Me.City & "','" & Me.TxtAmtpdTotal & "','" & _
Me.DateRec & "','" & Me.Notified & "','" & _
Me.DateNotice & "','" & Me.AcctID & "','" & Me.TaxType & "','" & Me.Period & "','" & _
Me.NoticeReason & "','" & Me.Resolution & "','" & Me.TaxDue & "','" & Me.IntDue & "','" & Me.PenDue & "','" & _
Me.DateRes & "','" & Me.AmtPdInt & "','" & Me.AmtpdPen & "','" & Me.AmtpdTax & "','" & _
Me.Assigned & "','" & Me.txtsubass & "','" & Me.Resolved & "')", dbFailOnError
MsgBox ("Entry Added")
Use a string variable to hold the INSERT statement. That allows you to Debug.Print the string so you can inspect the actual statement your code created. And you can Execute the string.
Dim strInsert As String
strInsert = "INSERT INTO NLog(IDKEY, Company, CoName, State, City, AmtpdTotal, DateRec, Notified, DateNotice, AcctID, TaxType, Period, NoticeReason, Resolution, TaxDue, Intdue, PenDue, Dateres, Amtpdint, amtpdpen, amtpdtax, Assigned, subAssgn, Resolved) " & _
" VALUES(" & Me.TxtIDKEY & ",'" & Me.Company & "','" & Me.CoName & "','" & _
Me.State & "','" & Me.City & "','" & Me.TxtAmtpdTotal & "','" & _
Me.DateRec & "','" & Me.Notified & "','" & _
Me.DateNotice & "','" & Me.AcctID & "','" & Me.TaxType & "','" & Me.Period & "','" & _
Me.NoticeReason & "','" & Me.Resolution & "','" & Me.TaxDue & "','" & Me.IntDue & "','" & Me.PenDue & "','" & _
Me.DateRes & "','" & Me.AmtPdInt & "','" & Me.AmtpdPen & "','" & Me.AmtpdTax & "','" & _
Me.Assigned & "','" & Me.txtsubass & "','" & Me.Resolved & "')"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailOnError
You can then view the completed statement (the output from Debug.Print) in the Immediate window. Ctrl+g will take you to the Immediate window.
If the error is not obvious, you can copy the statement text, create a new query in the query designer, switch it to SQL View, and paste in the copied statement. When you try to run that query from the designer, Access will display a parameter dialog which asks you to supply a value for the parameter. Notice that dialog also includes the "name" of the parameter. Frequently the cause of this problem is a misspelled field name --- since Access can't find a field by that name, it assumes it must be a parameter instead.
Alternatively, you can use VBA code to show you the names of any parameters in your query:
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim prm As DAO.Parameter
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strInsert)
For Each prm In qdf.Parameters
Debug.Print prm.Name
Next

how to vb.net date save to mysql date with no 0000-00-00

I've been killing brain cell for over 5 hours with this question.
how to properly save a date from vb.net to mysql date without getting the 0000-00-00all the time.
I have tried multiple suggestions where you format the date value before entering but it gets me the same result ex:
Dim departDate As Date
Dim d As String = Format(departDate, "05/05/2007")
in which i tested and didnt works i still got the 0000-00-00
I've tried:
Dim changeFormatDate As Date
Dim AddFechaListadoCasas2 as String
changeFormatDate = AddCasasListadoDatePicker.Text
AddFechaListadoCasas2 = changeFormatDate.ToString("yyyy-MM-dd")
which still gives me on mysql the 0000-00-00
I also tried this example:
Dim myDate as DateTime = DateTime.ParseExact(x, "yyyy-MM-dd", CultureInfo.CurrentCulture)
and trying to save to mysql still gave me the 0000-00-00
in my program im grabbing the date from a datepicker as text then swtich it to a string and try to save it to the database like that. if necessary i would love to convert it to a date with the format yyyy-MM-dd which is necessary for MySQL but everything i've done above it still shows me the 0000-00-00 which is frustrating.
any help would be very appreciated it.
Leo
here is the MySQL insert statement i have on my program.
AddFechaListadoCasas2 = AddCasasListadoDatePicker.Text
AddFechaCierreCasas2 = AddFechaCierreCasas.Text
SqlVentaCasas = "INSERT INTO VentaCasas (ID, Direccion, Ciudad_Municipio, Zona_Localidad, Barrio, " & _
"Estatus, Precio, Unidad, Departamento, Conjunto, Estrato, Matricula_Inmobiliaria, Cedula_Catastral," & _
"Escritura, Notaria, Ano, Area_Metros_2, Tipo_de_Construccion, Niveles, Habitaciones, Garajes," & _
"Techo, Vista, Picina, Cocina_Integral, Bar, Cuarto_Bano_Servicio, Antejardin, Equipos," & _
"Aire_Acondicionado, Detalles_addicionales, Estilo, Ano_Construccion, Orientacion, Banos, Parqueos," & _
"Piso, Balcon, Jacuzzi_Sauna, Chimenea, Hall_Television, Zona_lavanderia, Patio, Accesorios," & _
"Calefaccion, Administracion, Amenidades, Impuestos, Condiciones, Ocupacion," & _
"Cuota_Administracion, Restricciones, Seguridad, Mostrar, Comision, Fecha_Listado, " & _
"Agente_Cooperante, Fecha_Expiracion, CiudadEscritura, Agente, Licensia, Compania, NumeroPersonal," & _
"NumeroCompania, NumeroFax, Email, AreaLotesM2, PrecioOriginal, Account_Creator, NumeroDias ) VALUES ('" & _
AddIDCasas2 & "','" & _
AddDireccionCasas2 & "','" & AddCiudadCasas2 & "','" & AddZonaCasas2 & "','" & AddBarrioCasas2 & "','" & _
AddEstatusCasas2 & "'," & AddPrecioCasas2 & ",'" & AddUnidadCasas2 & "','" & AddDepartamentoCasas2 & "','" & _
AddConjuntoCasas2 & "'," & AddEstratoCasas2 & ",'" & AddMatriculaCasas2 & "','" & _
AddCedulaCatastralCasas2 & "','" & AddEscrituraCasas2 & "','" & AddNotariaCasas2 & "'," & _
AddAnoCasas2 & "," & AddMetros2Casas2 & ",'" & AddTipoConstruccionCasas2 & "'," & _
AddNivelesCasas2 & "," & AddHabitacionesCasas2 & "," & AddGarajesCasas2 & ",'" & _
AddTechoCasas2 & "','" & AddVistaCasas2 & "','" & AddPicinaCasas2 & "','" & AddCocinaIntegralCasas2 & "','" & _
AddBarCasas2 & "','" & AddCuartoCasas2 & "','" & AddAnteJardinCasas2 & "','" & AddEquiposCasas2 & "','" & _
AddAireAcondicionadoCasas2 & "','" & AddDetallesAddicionalesCasas2 & "','" & AddEstiloCasas2 & "'," & _
AddAnoConstruccionCasas2 & ",'" & AddOrientacionCasas2 & "'," & AddBanoCasas2 & "," & _
AddParqueoCasas2 & ",'" & AddPisoCasas2 & "','" & AddBalconCasas2 & "','" & AddJacuzziCasas2 & "','" & _
AddChimeneaCasas2 & "','" & AddTVCasas2 & "','" & AddZonaLavanderiaCasas2 & "','" & AddPatioCasas2 & "','" & _
AddAccesoriosCasas2 & "','" & AddCalefaccionCasas2 & "','" & AddAdministracionCasas2 & "','" & _
AddAmenidadesCasas2 & "','" & AddImpuestosCasas2 & "','" & AddCondicionesCasas2 & "','" & _
AddOcupacionCasas2 & "','" & AddCuotaAdministracionCasas2 & "','" & AddRestriccionesCasas2 & "','" & _
AddSeguridadCasas2 & "','" & AddMonstrarCasas2 & "','" & AddComisionCasas2 & "','" & _
AddFechaListadoCasas2 & "','" & AddAgenteCooperanteCasas2 & "','" & _
AddFecdhaExpiracionCasas2 & "','" & _
AddCiudadEscrituraCasas2 & "','" & AgenteNameCasas2 & "','" & _
AgenteLicensiaCasas2 & "','" & AgenteCompaniaCasas2 & "','" & _
AgentePersonalCasas2 & "','" & AgenteTelefonoCasas2 & "','" & _
AgenteFaxCasas2 & "','" & AgenteEmailCasas2 & "'," & AddAreaLotesM2Casas2 & "," & AddPrecioOriginalCasas2 & ", '" & AgenteAccountCreatorCasas2 & "', 0 );"
AddFechaListadoCasas2 and AddFecdhaExpiracionCasas2 are Strings that contains the date i want to input on MySQL
Your current query is vulnerable with SQL Injection. Please make use of ADONet Object such as Connection and Command with parameters. To be more specific, since you are using MySQL, use MySQL Data provider. It will automatically cast the data types for you.
Dim query As String = "INSERT INTO tableName (dateColumn) VALUES (#dateParam)"
Using conn As New MySqlConnection("connectionstringHere")
Using comm As New MySqlCommand()
With comm
.Connection = conn
.CommandText = query
.CommandType = Commandtype.Text
' Assuming this is a DatePicker '
.Parameters.AddWithValue("#dateParam", AddCasasListadoDatePicker.Value)
End With
Try
conn.Open()
comm.ExecuteNonQuery()
Catch(ex as MySqlException)
Msgbox(ex.Message.ToString())
End Try
End Using
End Using