Add case statement in insert query to turn empty string into null - mysql

I am trying to insert values from an Excel VBA userform to MySQLDBA.
The problem comes with empty text box values for date columns.
MySQL doesn't accept " but it allows Null.
Can I add a case statement in my insert query to check if the value for the column is empty string, and if it is, insert null for that column? Otherwise, it should insert the value of the textbox.
Here is my current query in VBA, where Date_of_Birth columns should be checked for empty string:
Str = "insert into sample.details (ID,Name,Age,Gender,Date_of_Birth) values ('" & txt1.Value & "', '" & txt2.Value & "','" & txt3.Value & "','" & txt4.Value & "','" & txt5.Value & "');"
P.S I tried setting a if condition for the txt5.value but that didn't work.

You can use the IIf function.
Str = "insert into sample.details (ID,Name,Age,Gender,Date_of_Birth) values ('" & txt1.Value & "', '" & txt2.Value & "','" & txt3.Value & "','" & txt4.Value & "'," & IIf(txt5.Value="","null","'" & txt5.Value & "'") & ");"

Related

VBA SQL Replace Into Syntax Error

I have the following query and do have a problem with the syntax.
The query code looks like this:
query = "REPLACE INTO valuation (`ticker`,`depot_id`,`src_id`,`valuation_date`,`value`) VALUES ('" & strTicker & "','" & intDepot & "','" & intSrc & "','" & dateValuationDate & "','" & Format(CDbl(dblMktValue), "000") & "');"
which gives me the following string:
REPLACE INTO valuation (`ticker`,`depot_id`,`src_id`,`valuation_date`,`value`) VALUES ('BK001EUR','1','2','09.08.2017','14999260');
The fields are:
Varchar, Int, Int, Date, double
i guess i do have some problems with the quotations, but I am not sure how to fix it.
Thank you
You are likely getting errors on your numeric data, so you need to remove the unneeded quotes. Try this:
query = "REPLACE INTO valuation (`ticker`,`depot_id`,`src_id`,`valuation_date`,`value`) VALUES ('" & strTicker & "'," & intDepot & "," & intSrc & ",'" & dateValuationDate & "'," & Format(CDbl(dblMktValue), "000") & ");"

How to display values from multiple textbox(vb net) to mysql database in column form

I have a database in MySQL named database1 and a table named records. I am trying to add the contents on my textboxes(3 textboxes) to my MySQL database in column form, not in row form.
Is it possible with concat???
The output I want
Here is my code, I created a row for typeofservice2, and typeofservice3but I only want one, which is type of service, and it looks like this
What I did
Query = "insert into database1.records (dateoftrans,typeofservice,typeofservice2,typeofservice3) values('" & TextBox12.Text & "','" & tos & "','" & tos2 & "','" & tos3 & "')"
tos, tos2, and tos3 are my textboxes
Hope someone can help me
At first the question for me is quite tricky but then I get your point, I give it a shot.
your current query is this.
Query = "insert into database1.records (dateoftrans,typeofservice,typeofservice2,typeofservice3) values('" & TextBox12.Text & "','" & tos & "','" & tos2 & "','" & tos3 & "')"
The best way i can give to you is this..
Create 3 x Insert Command and each Query has there own tos(textbox name). do something like this.
Query1 = insert into database1.records(dateoftrans,typeofservice) values('" & TextBox12.Text & "','" & tos & "')
Query2 = insert into database1.records(dateoftrans,typeofservice) values('" & TextBox12.Text & "','" & tos2 & "')
Query2 = insert into database1.records(dateoftrans,typeofservice) values('" & TextBox12.Text & "','" & tos3 & "')
by that you can save all the values in same column.

vb.net INSERT CURDATE() to MySQL issue

In a windows application I have a query that im trying to insert the current date on my mysql database
query below:
SqlVentaCasas1 = "INSERT INTO VentaCasasHistory (ID, Direccion, Estatus, Precio, " & _
"NumeroDias, FechaHoy, Agente, Compania, Unidad, Ciudad ) VALUES ('" & _
AddIDCasas2 & "','" & AddDireccionCasas2 & "','" & AddEstatusCasas2 & "'," & AddPrecioCasas2 & ", 0, CURDATE(), '" & AgenteNameCasas2 & "','" & AgenteCompaniaCasas2 & "', '" & AddUnidadCasas2 & "', '" & AddCiudadCasas2 & "' );"
CommandVentaCasas1 = New MySqlCommand(SqlVentaCasas1, con)
CommandVentaCasas1.CommandType = CommandType.Text
CommandVentaCasas1.ExecuteNonQuery()
when i input the values that i want to insert into mysql everything runs smoothly except that when i check the database for the date entered i find myself with the 0000-00-00
on the other hand, when i run the same query from PHPmyAdmin
INSERT INTO `VentaCasasHistory`(`ID`, `Direccion`, `Estatus`, `Precio`, `NumeroDias`, `FechaHoy`, `Agente`, `Compania`, `Unidad`, `Ciudad`) VALUES ([String1],[String2],[String3],[Integer1],[Integer2],CURDATE(),[String4],[String5],[String6],[String7])
where FechaHoy is CURDATE() is does insert correctly the date that should be.
I cant seem to find what is the problem, As i understand it will only insert 0000-00-00 if there is something wrong with the date when been entered.
the reason i kept both queries "identical" was to understand what im doing wrong and I know that they can be subject to SQL injection.
your help would be very appreciated.
Leo P.
this is the code i have for the last piece that you told me.
Dim StringDate As String
StringDate = Date.Today.ToString("yyyy-MM-dd")
SqlVentaCasas1 = "INSERT INTO VentaCasasHistory (ID, Direccion, Estatus, Precio, " & _
"NumeroDias, FechaHoy, Agente, Compania, Unidad, Ciudad ) VALUES ('" & _
AddIDCasas2 & "','" & AddDireccionCasas2 & "','" & AddEstatusCasas2 & "'," & AddPrecioCasas2 & ", 0, STR_TO_DATE('" & StringDate & "', GET_FORMAT(DATE,'ISO')), '" & AgenteNameCasas2 & "','" & AgenteCompaniaCasas2 & "', '" & AddUnidadCasas2 & "', '" & AddCiudadCasas2 & "' );"
unfortunately it does not work and i still get the 0000-00-00.
CURDATE() should really be specified as default value used in CREATE TABLE. In other words, you don't need to put it in as part of a query as when you insert a new record the field with default value set to CURDATE() will have the date automatically inserted.
F.ex:
CREATE TABLE MyTable
(
ID int NOT NULL,
MyName varchar(30) NOT NULL,
MyDate datetime NOT NULL DEFAULT CURDATE(),
PRIMARY KEY (ID)
)
INSERT INTO MyTable (MyName) VALUES ('Epistemex')
Will set the MyDate field to CURDATE().
Hope this helps.

quickly insert data to remote mysql server in vb.net

I have small application in vb.net
I have one table in msaccess, which is having around 20,000 records,
now, I want to insert these records to remote server of mysql,
I tried as below code, it takes around 3-4 hours to insert data,
Can anyone show me faster way to insert data, i will be very glad..
dst in code is having all records from ms Access
For i As Integer = 0 To dst.Tables(0).Rows.Count - 1
mycmd.Connection = mycn
str = "INSERT INTO tblstudentresults(department_desc, grade, roll_no, name, course_code, course_desc, examination_type, total_marks, obtained_marks)"
/*'str = str & " VALUES('" & cname & "','" & sdr("grade").ToString() & "','" & sdr("st_code").ToString() & "','" & sdr("stName").ToString() & "','" & sdr("Subject_code").ToString() & "','" & sdr("Subject").ToString() & "','" & sdr("ExamTitle").ToString() & "','" & sdr("Maxmark").ToString() & "','" & sdr("score").ToString() & "')" -- Added non-VB comment here to improve readability */
str = str & " VALUES('" & cname & "', '" & dst.Tables(0).Rows(i)("grade").ToString() & "', '" & dst.Tables(0).Rows(i)("st_code").ToString() & "', '" & dst.Tables(0).Rows(i)("stName").ToString() & "', '', '" & dst.Tables(0).Rows(i)("Subject").ToString() & "', '" & dst.Tables(0).Rows(i)("ExamTitle").ToString() & "', '" & dst.Tables(0).Rows(i)("Maxmark").ToString() & "', '" & dst.Tables(0).Rows(i)("score").ToString() & "')"
mycmd.CommandText = str
mycmd.ExecuteNonQuery()
next
It might be faster to construct a multiple-row insert in one large string (or maybe chunks of, say 500 rows), then run the entire insert statement in a single call, something roughly like the following:
Dim firstRow as Boolean = True
str = "INSERT INTO tblstudentresults(...) VALUES"
For i As Integer = 0 To dst.Tables(0).Rows.Count - 1
' Only insert comma after first row, so we don't have comma at the end.
If Not firstRow Then str = str & ","
str = str & "('" & cname & "','" ...
firstRow = False
Next
mycmd.Connection = mycn
mycmd.CommandText = str
mycmd.ExecuteNonQuery()

Listbox in Ms access

I can store records in the DB by using combobox with the following code.
Here single part number is selected and partnumber related data is stored in the DB table.
But I want the code for Listbox...When I select multiple partnumbers ..how can I store in the DB table?
Case "Pn ADDED to Wrapper", _
"Pn REMOVED from Wrapper"
If Me!PartNumber <> "All" And Me!PartNumber <> "Select" Then ' a proper part number has been selected in combo box
strNewSq5 = _
"INSERT INTO tblTmpEventLog (TrackingNumber,PartNumber,PartNumberChgLvl,EnteredBy,EventTypeSelected,EventDate)"
strNewSq5 = strNewSq5 & " VALUES ('" & tempTrackingNumber & "','" & _
tempPartNumber & "','" & _
tempPartNumberChgLvl & "','" & _
tempEnteredBy & "','" & _
tempEventTypeSelected & "'," & _
"#" & Forms!frmEventLog_Input.EventDate & "#)"
dbs.Execute strNewSq5, dbFailOnError
TrnsfTmpEventToEventLog
Else
displayMsgBox = MsgBox("A single part number must be specified. Please correct.", vbCritical, "System Error")
Exit Sub
End If
You need to iterate over the selected items and store them one by one:
MS Access 2007 - Cycling through values in a list box to grab id's for a SQL statement
EDIT re comment
You do not provide sufficient information for a detailed answer, but here are some notes that may help.
For Each itm In Me.NameOfListBox.ItemsSelected
If Instr("All,Select",Me.NameOfListBox.Column(0, itm) )=0 Then
'' a proper part number has been selected in list box
'' Me.NameOfListBox.Column(0, itm) is the column (zero in this example
'' and row (itm) of the selected item in the list box. If it is the
'' part number, then you might like to say:
'' tempPartNumber = Me.NameOfListBox.Column(0, itm)
strNewSq5 = "INSERT INTO tblTmpEventLog " & _
"(TrackingNumber,PartNumber,PartNumberChgLvl,EnteredBy," & _
"EventTypeSelected,EventDate)"
strNewSq5 = strNewSq5 & " VALUES ('" & tempTrackingNumber & "','" & _
tempPartNumber & "','" & _
tempPartNumberChgLvl & "','" & _
tempEnteredBy & "','" & _
tempEventTypeSelected & "'," & _
"#" & Forms!frmEventLog_Input.EventDate & "#)"
dbs.Execute strNewSq5, dbFailOnError
TrnsfTmpEventToEventLog
Else
''Do not insert
End If
Next