Actually i'm formatting data to insert in my MySQL DB and i'm at the point where i'm managing the NULL values.
So for manage it i've set a try catch inside the if where i look for datatype and now i have to put in the Catch exception the default value of certain type.
But how can i do it in VB.NET?
Here is my code, any suggestion for code improvment will be grateful
For Each row As DataRow In ds.Tables(0).Rows
righe = ""
For Each column As DataColumn In ds.Tables(0).Columns
If column.DataType = Type.GetType("System.DateTime") Then
Try
righe &= "'" & Format(row.Item(column.ColumnName), "yyyy-MM-dd") & "', "
Catch ex As Exception
End Try
ElseIf column.DataType = Type.GetType("System.TimeSpan") Then
righe &= "'" & Format(row.Item(column.ColumnName).ToString, "HH\:mm\:ss") & "', "
ElseIf column.DataType = Type.GetType("System.Int32") Then
righe &= row.Item(column.ColumnName) & ", "
ElseIf column.DataType = Type.GetType("System.Single") Then
righe &= Replace(row.Item(column.ColumnName), ",", ".") & ", "
ElseIf column.DataType = Type.GetType("System.Byte") Then
righe &= row.Item(column.ColumnName) & ", "
ElseIf column.DataType = Type.GetType("System.Double") Then
righe &= Replace(row.Item(column.ColumnName), ",", ".") & ", "
ElseIf column.DataType = Type.GetType("System.String") Then
righe &= "'" & APICI(row.Item(column.ColumnName)) & "', "
End If
Next
righe = Mid(righe, 1, Len(righe) - 2)
Next
Related
I can execute an Access SQL INSERT statement without error, but when I attempt an UPDATE with the code below, it throws the error:
"Syntax error in string in query expression".
Why does that happen and how can I fix it?
Here is my code..
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
If txtName.Text = Nothing Or dtpDateBirth.Text = Nothing Or txtPhoneNumber.Text = Nothing Or txtEmail.Text = Nothing Or txtID.Text = Nothing Or mtbNPWP.Text = Nothing Or rtbAddress.Text = Nothing Or txtVillage.Text = Nothing Or txtSubDistrict.Text = Nothing Or txtCity.Text = Nothing Or txtPostalCode.Text = Nothing Or txtEmergencyName.Text = Nothing Or txtEmergencyNumber.Text = Nothing Or txtEmergencyEmail.Text = Nothing Then
MsgBox("No data has been update", MsgBoxStyle.Information, "No data edit")
Exit Sub
Else
Call koneksi()
cmd = New OleDb.OleDbCommand("update t_customer set name='" & txtName.Text & "', date_birth='" & dtpDateBirth.Text & "', phone_number='" & txtPhoneNumber.Text & "', email='" & txtEmail.Text & "', id='" & txtID.Text & "', npwp='" & mtbNPWP.Text & "', address='" & rtbAddress.Text & "', village='" & txtVillage.Text & "', sub_district='" & txtSubDistrict.Text & "', city='" & txtCity.Text & "', postal_code='" & txtPostalCode.Text & "', gender='" & gen & "', emergency_name='" & txtEmergencyName.Text & "', phone_emergency='" & txtPhoneNumber.Text & "', email_emergency='" & txtEmergencyEmail.Text & "' where [codeCust]='" & txtIDCust.Text, conn)
cmd.ExecuteNonQuery()
MsgBox("Update data success!", MsgBoxStyle.Information, "Update")
End If
Call disabled()
Call showData()
End Sub
As HansUp has suggested with the link you should be using parameters. Also you are not disposing the command. Also AFAIK (I thought) you needed the open the connection before you can ExecuteNonQuery. As for the Data Mismatch youre experiencing, I think it's because you have a ' in the where clause that shouldnt be there, assuming that the ID is an INT.
Using OledbConn As New OleDbConnection("Conn String")
OledbConn.Open()
Using t_customerCMD As New OleDbCommand("UPDATE t_customer SET [Col1]=#Col1,[Col2]=#Col2 WHERE [codeCust]=#codeCust", OledbConn)
With t_customerCMD
.Parameters.Add("#Col1", SqlDbType.VarChar).Value = TextBox1.Text
.Parameters.Add("#Col2", SqlDbType.VarChar).Value = TextBox2.Text
.Parameters.Add("#codeCust", SqlDbType.Int).Value = CInt(txtIDCust.Text) 'Assumes ID is integer
.ExecuteNonQuery()
End With
End Using
OledbConn.Close()
End Using
End Sub
Thank you for everyone who helped me. I thank you very much. This problem has been resolved.
this is my completion code, which I can finally do to update the database.
Sub updateData()
Call gender()
If String.IsNullOrEmpty(txtName.Text) OrElse String.IsNullOrEmpty(dtpDateBirth.Text) OrElse String.IsNullOrEmpty(txtPhoneNumber.Text) OrElse String.IsNullOrEmpty(txtEmail.Text) OrElse String.IsNullOrEmpty(txtID.Text) OrElse String.IsNullOrEmpty(mtbNPWP.Text) OrElse String.IsNullOrEmpty(rtbAddress.Text) OrElse String.IsNullOrEmpty(txtVillage.Text) OrElse String.IsNullOrEmpty(txtSubDistrict.Text) OrElse String.IsNullOrEmpty(txtCity.Text) OrElse String.IsNullOrEmpty(txtPostalCode.Text) OrElse String.IsNullOrEmpty(txtEmergencyName.Text) OrElse String.IsNullOrEmpty(txtEmergencyNumber.Text) OrElse String.IsNullOrEmpty(txtEmergencyEmail.Text) Then
MsgBox("No data has been update", MsgBoxStyle.Information, "No data edit")
Exit Sub
Else
Try
Call koneksi()
Using cmd = New OleDb.OleDbCommand("update t_customer set name='" & txtName.Text & "', date_birth='" & dtpDateBirth.Text & "', phone_number='" & txtPhoneNumber.Text & "', email='" & txtEmail.Text & "', id='" & txtID.Text & "', npwp='" & mtbNPWP.Text & "', address='" & rtbAddress.Text & "', village='" & txtVillage.Text & "', sub_district='" & txtSubDistrict.Text & "', city='" & txtCity.Text & "', postal_code='" & txtPostalCode.Text & "', gender='" & gen & "', emergency_name='" & txtEmergencyName.Text & "', phone_emergency='" & txtPhoneNumber.Text & "', email_emergency='" & txtEmergencyEmail.Text & "' where [codeCust]=#codeCust", conn)
cmd.Parameters.Add("codeCust", CType(txtIDCust.Text, String))
cmd.ExecuteNonQuery()
conn.Close()
MsgBox("Update data success!", MsgBoxStyle.Information, "Update")
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
Because I use the radio button for gender options, I added this so that gender can be changed.
Private Sub gender()
Call koneksi()
Dim str As String
str = "Insert into t_customer([gender]) Values (?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, conn)
If rdnMale.Checked = True Then
gen = rdnMale.Text
cmd.Parameters.Add(New OleDbParameter("gender", CType(gen, String)))
Else
gen = rdnFemale.Text
End If
End Sub
so this is my code for inserting files and what i need to autoincrement the codes but the thing is i cant use the id since it has so many department in just one table for example
OP-BLDG-16-0001
LP-LAND-16-0001
codename.Text = "" & codedepartment.Text & "-" & code1.Text & "-" & Now.Date.ToString("yy") & "-" & "00" & ""
So thats what i did to get first 3 info and i just have to set it into autoincrement
Try
dataB = "INSERT into assetpp ( [codes],[codedepartmentname]) VALUES ( '" & codename.Text & "','" & codedepartment.Text & "')"
ConnDB()
cmd = New OleDbCommand(dataB, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
If i > 0 Then
MsgBox("Add Succesfully", MsgBoxStyle.Information, "Confirmation")
tableassetpp()
Else
MsgBox("Failed to add Data", MsgBoxStyle.Information, "Alert")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
Static cnt As Integer
cnt = cnt + 1
codename.Text = "" & codedepartment.Text & "-" & code1.Text & "-" & Now.Date.ToString("yy") & "-" & Format(cnt, "0000") & ""
i am working on windows application.i am taking value from my sql database then writing to one .txt file.i have a code like this:
sql = "select * from " & strtablename
cmd = New SqlCeCommand(sql, CONN)
dr = cmd.ExecuteReader()
ListBox1.Items.Add("Extracting " & strfilename)
ListBox1.Refresh()
While (dr.Read())
sw = New StreamWriter(hht_Memory & "\Export\" & strfilename & ".txt", True)
prcount = 0
fvalues = ""
For I = 0 To dr.FieldCount - 1
If fvalues = "" Then
fvalues = IIf(IsDBNull(dr(I)), "", dr(I))
fvalues = Trim(Replace(fvalues, "'", ""))
Else
fvalues = fvalues & ", "
fvalues = fvalues & IIf(IsDBNull(dr(I)), "", dr(I))
fvalues = Trim(Replace(fvalues, "'", ""))
End If
Next I
sw.WriteLine(fvalues)
prcount = prcount + 1
sw.Close()
this is writing to text file.but each value separated by comma.i want to separate each value by |.
what the changes i have to make in my code?
This line:
fvalues = fvalues & ", "
should be changed to:
fvalues = fvalues & "| "
here is my code to submit data to my csv file. How do I check to see if the data already exists before saving it.
Dim csvFile As String = My.Application.Info.DirectoryPath & "\HoseData.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
'If My.Computer.FileSystem.FileExists(csvFile) Then
'outFile.WriteLine("job number, sales order number, date, requested by, serial number, hose type, hose size, fitting 1, fitting 2, qty, oal, cut off, offset, crimp 1, crimp 2, cleaned, pigged", False)
'End If
outFile.WriteLine(TextBox1.Text & "," & TextBox2.Text & "," & """" & DateTimePicker1.Text & """" & "," & ComboBox1.Text & "," & TextBox3.Text & "," & ListBox2.Text & "," & ListBox3.Text & "," & TextBox11.Text & "," & TextBox12.Text & "," & NumericUpDown1.TextAlign & "," & TextBox4.Text & "," & TextBox5.Text & "," & TextBox6.Text & "," & TextBox9.Text & "," & TextBox10.Text & "," & ListBox4.Text & "," & ListBox5.Text)
MessageBox.Show("INPUT WAS SAVED")
Dim butt As System.Windows.Forms.Button = DirectCast(sender, System.Windows.Forms.Button)
butt.Enabled = False
'butt.Visible = False
outFile.Close()
Console.WriteLine(My.Computer.FileSystem.ReadAllText(csvFile))
Is this what you're looking for?
Dim fn As String = My.Application.Info.DirectoryPath & "\HoseData.csv"
Dim fileText As String
Dim outString As String = TextBox1.Text & "," & TextBox2.Text & "," & """" & DateTimePicker1.Text & """" & "," & ComboBox1.Text & "," & TextBox3.Text & "," & ListBox2.Text & "," & ListBox3.Text & "," & TextBox11.Text & "," & TextBox12.Text & "," & NumericUpDown1.TextAlign & "," & TextBox4.Text & "," & TextBox5.Text & "," & TextBox6.Text & "," & TextBox9.Text & "," & TextBox10.Text & "," & ListBox4.Text & "," & ListBox5.Text
Using reader As StreamReader = File.OpenText(fn)
fileText = reader.ReadToEnd
End Using
Using outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(fn, True)
If fileText.Contains(outString) Then
'do stuff when the string is already present, e.g.:
MessageBox.Show("You've already entered that one.")
Else
'do stuff when it isn't, e.g.:
outFile.WriteLine(outString)
End If
End Using
Right now I am building a filter based on user input (textboxes and comboboxes) by a bunch of if statements. There must be a better way. Here is my current code:
Private Function BuildProductsFilter() As String
Dim RawFilterResults As String = ""
If Not CompanyNameComboBox.SelectedValue Is Nothing AndAlso Not CompanyNameComboBox.SelectedValue.ToString = "[ALL]" Then
RawFilterResults = "companyname = '" & CompanyNameComboBox.SelectedValue.ToString & "'"
End If
If QtyTextbox.Text > "" AndAlso IsNumeric(QtyTextbox.Text) Then
RawFilterResults &= " and stock = " & QtyTextbox.Text
End If
If KeywordTextbox.Text > "" Then
RawFilterResults &= " and (description like '%" & KeywordTextbox.Text & "%'"
RawFilterResults &= "or descriptionlong like '%" & KeywordTextbox.Text & "%'"
RawFilterResults &= "or details like '%" & KeywordTextbox.Text & "%')"
End If
If SKUTextbox.Text > "" Then
If SKUTextbox.Text.StartsWith("*") Then
RawFilterResults &= " and sku like '%" & SKUTextbox.Text & "'"
ElseIf SKUTextbox.Text.EndsWith("*") Then
RawFilterResults &= " and sku like '" & SKUTextbox.Text & "%'"
Else
RawFilterResults &= " and sku = '" & SKUTextbox.Text & "'"
End If
End If
If Not AllowPurchaseCombobox.SelectedItem Is Nothing AndAlso Not AllowPurchaseCombobox.SelectedItem.ToString = "[ALL]" Then
RawFilterResults &= " and allowpurchase = '" & AllowPurchaseCombobox.SelectedValue.ToString & "'"
End If
If Not ShowPriceCombobox.SelectedItem Is Nothing AndAlso Not ShowPriceCombobox.SelectedItem.ToString = "[ALL]" Then
RawFilterResults &= " and showprice = '" & ShowPriceCombobox.SelectedValue.ToString & "'"
End If
If Not VirtualLoupeCombobox.SelectedItem Is Nothing AndAlso Not VirtualLoupeCombobox.SelectedItem.ToString = "[ALL]" Then
RawFilterResults &= " and VirtualLoupe = '" & VirtualLoupeCombobox.SelectedValue.ToString & "'"
End If
If ImageTextbox.Text > "" Then
Dim ImageDir As String = Path.GetDirectoryName(ImageTextbox.Text)
RawFilterResults &= " and imageurl like '" & ImageDir & "%'"
End If
If CaratTextbox.Text > "" Then
RawFilterResults &= " and carat = '" & CaratTextbox.Text & "'"
End If
If CutTextbox.Text > "" Then
RawFilterResults &= " and cut = '" & CutTextbox.Text & "'"
End If
If ColorTextbox.Text > "" Then
RawFilterResults &= " and color = '" & ColorTextbox.Text & "'"
End If
If ClarityTextbox.Text > "" Then
RawFilterResults &= " and Clarity = '" & ClarityTextbox.Text & "'"
End If
If RawFilterResults.StartsWith(" and ") Then
RawFilterResults = RawFilterResults.Substring(4)
End If
Return RawFilterResults
End Function
Use a fluent style interface. Simple sample here
Or better yet use and ORM so you don't have string encoded field names etc