Inserting the current datetime in vb.net(DateTime to String Conversion) - vb.net

I'm suppose to enter datatime to the database by passing this query
Dim regDate As DateTime = DateTime.Now
Dim strDate As String = regDate.ToString("yyyyMMddHHmmss")
I pass the "strDate" to the query,data type of my database table is datetime
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & regDate & "')")"
but it's getting error saying that
conversion failed when converting date and/or time from character string.
Help me to solve this problem

Dim regDate As DateTime = DateTime.Now
Dim strDate As String = regDate.ToString("yyyy-MM-dd HH:mm:ss")
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & strDate & "')")"

you have to pass strDate in query.Always use paremeterized query to avoid SQL injection
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & strDate & "')")"

May this works for you, at least it works for me on an acces db
Try
Dim cn As New OleDbConnection("your conection string here")
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
Dim sSQL As String = "insert into UserInfo(Date) values(#d1)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, cn)
Dim date As OleDbParameter = New OleDbParameter("#d1", OleDbType.Date, 15)
date.Value = DateTimePicker1.Text.ToString()
cmd.Parameters.Add(date)
If cmd.ExecuteNonQuery() Then
cn.Close()
MsgBox("successfully... ", MsgBoxStyle.Information, "Record Saved")
Else
MsgBox("failed... ", MsgBoxStyle.Critical, "Registration failed")
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Data Error")
Exit Sub
End Try
i hope this helps you,
regards Tom

Related

Custom date format for inserting date in mysql database

I have tried this code but the date format keeps staying the same when the record is entered
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString =
Dim reader As MySqlDataReader
Try
mysqlconn.Open()
Dim query As String
query = "insert into jadco_test.adrv (id,type_adrv,date_discov,date_notif,pssd,psed,comment,hearing_date,sanction`enter code here`_sd,sanction_ed) values('" & Tbox_ID.Text & "','" & ComboBox_adrv.SelectedItem & "', '" & DateTimePicker_DD = DateTime.Now.ToString("yyyy-MM-dd") & "','" & DateTimePicker_DN.CustomFormat & "','" & DateTimePicker_pssd.CustomFormat & "','" & DateTimePicker_psed.CustomFormat & "', '" & TextBox_comment.Text & "','" & DateTimePicker_HD.CustomFormat & "','" & DateTimePicker_SSD.CustomFormat & "','" & DateTimePicker_SED.CustomFormat & "' )"
command = New MySqlCommand(query, mysqlconn)
reader = command.ExecuteReader
MessageBox.Show("record saved")
mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mysqlconn.Dispose()
End Try

How to Enter 3 Textbox value into one fieldname

This is my Code I want to Enter First_Name,Middle_name and Last_Name in one Fieldname
Try
MysqlConn.Open()
Dim Query As String
Query = "INSERT INTO residentrecords.info (id,last_name,first_name,middle_name,age,address,contact_no,date_of_birth,religion,civil_status,education_attainment,occupation,fathers_name,mothers_name,mothers_occupation,fathers_occupation,gender,purok,blotter,docu,voter) values ('" & add.TextBox_ID.Text & "','" & add.TextBox_LN.Text & "','" & add.TextBox_FN.Text & "','" & add.TextBox_MN.Text & "','" & add.TextBox_Age.Text & "','" & add.TextBox_Address.Text & "','" & add.TextBox_Contact.Text & "','" & add.DateTimePicker1.Text & "','" & add.ComboBox_religion.Text & "','" & add.ComboBox_CS.Text & "','" & add.TextBox_Educ.Text & "','" & add.TextBox_Occu.Text & "','" & add.TextBox1_FathersName.Text & "','" & add.TextBox1_MothersName.Text & "','" & add.TextBox_mothersocc.Text & "','" & add.TextBox_fathersocc.Text & "','" & add.ComboBox_gender.Text & "','" & add.rpurok.Text & "','0','0','" & add.voter.Text & "')"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
MessageBox.Show("Successfully Registered!", "REGISTERED", MessageBoxButtons.OK, MessageBoxIcon.None)
If vbOK = MsgBoxResult.Ok Then
Me.Dispose()
add.Dispose()
add.Enabled = True
residents.Show()
End If
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
That's quite easy in .net. You need to split one string on it's whitespaces and insert the substrings seperately.
Use somethiing like this
Dim names as String()
Dim firstName as String
Dim middleName as String
Dim lastName as String
names = add.TextBox_Name.Text.Split(" ")
firstName = names(0)
middleName = names(1)
lastName = names(2)
You might check the array length by forehand to make sure the user really has a middle name. Or even more than one. I have two. Just check for names.length.
I hope i didn't misinterpreted your question. It was quite short explained.

Am trying to update data on vb.net with access database but the data does not update and there is no error

I have declared sql, cmd and cnt on public class, and also i have declare my database on Module.
Dim sql As String
Dim cmd As OleDb.OleDbCommand
Dim cnt As Long
Try
sql = "UPDATE [LDF] SET [Group_Code] = '" & ComboBox1.Text & "',
[Loan_Disb] ='" & TextBox1.Text & "',
[No_Of_Instalment] = '" & ComboBox2.Text & "',
[Single_Instalment]='" & TextBox2.Text & "',
[Loan_Security]='" & TextBox3.Text & "',
[Total_Amnt_TR]='" & TextBox4.Text & "',
[Member_Name]='" & TextBox5.Text & "',
[Group_Name]='" & TextBox6.Text & "',
[Date_Of_Disb]='" & DateTimePicker1.Value & "'
WHERE [Member_Number] = ' & ComboBox3.Text & '"
cmd = New OleDb.OleDbCommand(sql, Con)
cnt = cmd.ExecuteNonQuery
MsgBox("RECORD HAVE SUCCESSFUL UPDATED")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try

Error: data type mismatch criteria expression

This is my problems at VB.net 2012, when I'm run, show this error: data type mismatch criteria expression
Public Sub AddPOS()
vatAmount = Format((lblTotalCost.Text * 0.12), "#,##0.00")
nonVatAmount = Format(lblTotalCost.Text - vatAmount, "#,##0.00")
Try
sqL = "INSERT INTO POS(InvoiceNo, POSDate, POSTime, NonVatAmount, VatAmount, TotalAmount, StaffID, CustomerNo) VALUES('" & lblInvoiceNo.Text & "', '" & Format(Date.Now, "Short Date") & "', '" & Format(Date.Now, "Long Time") & "', '" & nonVatAmount & "', '" & vatAmount & "', '" & lblTotalCost.Text & "', '" & frmMain.lblEmployeeNo.Text & "'," & Val(lblCustomerNo.Text) & ")"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub

Conversion failed when converting date and/or time from character string

sql = "insert into tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)"
sql = sql & "values('" & txtNurseid.Text & "','" & TxtNursename.Text & "','" & Cmbdept.Text & "',convert(date,'" & DateTimePicker1.Value & "',103),convert(date,'" & DateTimePicker2.Value & "',103),'" & Txtqualification.Text & "','" & txtsalary.Text & "')"
conn.Execute(sql)
You should use sql-parameters to avoid sql-injection and to prevent from conversion issues like this.
Example presuming SQL-Server:
Const sql = "INSERT INTO tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)" & vbCrLf & _
"VALUES(#nurseid, #nursename, #deptname, #dob, #doj, #qualification, #salary)"
Using con = New SqlConnection("Insert Your Connection String Here")
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#nurseid", txtNurseid.Text)
cmd.Parameters.AddWithValue("#nursename", TxtNursename.Text)
cmd.Parameters.AddWithValue("#deptname", Cmbdept.Text)
' -- No conversion problems anymore because you pass a DateTime -- '
cmd.Parameters.AddWithValue("#dob", DateTimePicker1.Value)
' ... other parameters ... '
con.Open()
Dim affectedRecords As Int32 = cmd.ExecuteNonQuery()
End Using
End Using
Try to change like this ..
sql = "insert into tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)"
sql = sql & " values('" & txtNurseid.Text & "','" & TxtNursename.Text & "','" & Cmbdept.Text & "',#" & format(DateTimePicker1.Value.Date) & "#,#" & format(DateTimePicker2.Value.Date) & "#,'" & Txtqualification.Text & "','" & txtsalary.Text & "')"
conn.Execute(sql)
As Tim Scmelter said .. you better use parameterize input
Add Parameters as below and it works like charm
cmnd.Parameters.Add("#date_time", SqlDbType.DateTime).Value = datetime.Date;
The original post is here:
https://www.codeproject.com/Answers/552202/Conversionplusfailedpluswhenplusconvertingplusdate#answer3