Conversion failed when converting date and/or time from character string - vb.net

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

Related

Number of query values and destination fields are not the same. Error in vb.net

I'm using Microsoft Visual Studio 2010 Express and I'm trying to make a enrollment form using VB.NET. This is my code so far:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cardStr As String
Dim formStr As String
Dim birthStr As String
Dim goodmoralStr As String
If cbcard.Checked Then
cardStr = "OK"
Else
cardStr = ""
End If
If cbform.Checked Then
formStr = "OK"
Else
formStr = ""
End If
If cbbirth.Checked Then
birthStr = "OK"
Else
birthStr = ""
End If
If cbgoodmoral.Checked Then
goodmoralStr = "OK"
Else
goodmoralStr = ""
End If
Dim cmd As New OleDbCommand
Dim conn As New OleDbConnection(conStr)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into tblEnroll(StudID,StudLevel,StudFName,StudMName,StudLName,StudGender,StudBirthday,StudNationality,StudContact,StudPOB,StudCitizenship,StudReligion,MomName,MomContact,MomOccupation,DadName,DadContact,DadOccupation,PrevSchool,Card,F137,BirthCertificate) values ('" & txtID.Text & "','" & lbGrade.Text & "','" & txtFName.Text & "','" & txtMName.Text & "','" & txtLName.Text & "','" & lbGender.Text & "','" & dtpBirthDate.Text & "','" & txtNationality.Text & "','" & txtStudContact.Text & "','" & txtPOB.Text & "','" & txtCitizen.Text & "','" & txtReligion.Text & "','" & txtMom.Text & "','" & txtMomContact.Text & "','" & txtMomOccupation.Text & "','" & txtDad.Text & "','" & txtDadContact.Text & "','" & txtDadOccupation.Text & "','" & txtPrevSchool.Text & "','" & cardStr & "','" & formStr & "','" & birthStr & "','" & goodmoralStr & "')"
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show("Student Successfully Enrolled!")`
What could be the solution here?
You have one too many columns in your INSERT statement values. The value goodmoralStr does not have a corresponding column to insert into.
As a slight aside, you really should use parameterised SQL in your code to avoid issues with SQL injection.

Automation error using SQL queries in a loop

I'm trying to run a loop through a table that takes relevant information and then inserts it into a VFP9 .dbf table. However, I keep getting an automation error ('-2147217913 (80040e07)'). It seems to run the first time just fine, inserting into a table a single time before erroring out. I've made it print out the string every time with the execution part of the code commented out, but the SQL looks perfectly fine. What is the issue here?
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
sConnString = "DSN=Visual FoxPro Tables;UID=;SourceDB=s:\accounting\db;SourceType=DBF;Exclusive=No;BackgroundFetch=Yes;Collate=Machine;Null=Yes;Deleted=Yes;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
For i = 1 To [RawTable].Rows.Count
vStatement = "dong!"
vAccount = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("account").Index)
vCardUser = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("card member").Index)
vDate = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("date").Index)
vDesc = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("description").Index)
vAmount = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("amount").Index)
MsgBox "INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "','" & vDate & "','" & vDesc & "'," & vAmount & ")"
conn.Execute ("INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "','" & vDate & "','" & vDesc & "'," & vAmount & ")")
Next i
MsgBox "done :)", vbInformation
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
EDIT: Here is an example of what the table will look like.
date receipt description card member account # amount account
07/01/2016 Purchase Employee XXXX-XXXXXX-XXXXX 9.95 41000-000-00
07/01/2016 Purchase Employee XXXX-XXXXXX-XXXXX 33 41000-000-00
06/29/2016 Purchase Employee XXXX-XXXXXX-XXXXX 64 41000-000-00
Visual Foxpro doesn't like receiving dates as just String literals or series of numbers. Try using the CTOD function (Characters to Date) and see if that resolves the problem. The Execute line should look like:
conn.Execute ("INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "',CTOD('" & vDate & "'),'" & vDesc & "'," & vAmount & ")")

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

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

SQL injection in Visual Basic 2010

I don't know how to avoid SQL injection, could someone help me with my problem?
Here is my current code:
Private Function INSERT() As String
Dim SQLcon As New SqlConnection
Dim SQLdr As SqlDataReader
Try
SQLcon.ConnectionString = "Data Source=#####;Initial Catalog=OJT;Persist Security Info=True;User ID=####;Password=#####"
Dim SQLcmd As New SqlCommand("INSERT INTO dbo.Patients(pIDNo,pLName,pFName,pMI,pSex,pStatus,pTelNo,pDocID,pAddr,pStreet,pBarangay,pCity,pProvince,pLNameKIN,pFNameKIN,pMIKIN,pRelationKIN) VALUES('" & LabelPNumber.Text & "','" & txtLname.Text & "','" & txtFname.Text & "','" & txtMI.Text & "','" & txtPatientSex.Text & "','" & txtPatientSex.Text & "','" & txtPatientTelNo.Text & "','" & txtPatientDoctor.Text & "','" & txtStreetNumber.Text & "','" & txtStreetName.Text & "','" & txtBarangay.Text & "','" & txtCity.Text & "','" & txtProvince.Text & "','" & txtKinLname.Text & "','" & txtKinFname.Text & "','" & txtKinMI.Text & "','" & txtRelationToPatient.Text & "') ", SQLcon)
SQLcon.Open()
MsgBox("Patient Added!", MsgBoxStyle.Information)
SQLdr = SQLcmd.ExecuteReader()
Catch ex As Exception
MessageBox.Show("Error Occured, Can't Add Patient!" & ex.Message)
Finally
SQLcon.Close()
End Try
Return "done"
End Function
Basically anywhere you're concatenating strings together to create your SQL statement, especially that which comes from user input, is vulnerable.
Instead of doing this use SQL parameters, which can be added to the Parameters property of your SQL command (SQLcmd here).
I'll show you an example with one of your parameters - change your SQLCommand text to:
INSERT INTO dbo.Patients(pIDNo, ...)
VALUES(#pIDNo, ...)
Where #pIDNo is a "placeholder" in the string for the parameter value, which is sent separately from the command in the SQLParameters collection.
Then you can add a parameter with the same name as this "placeholder", and the value (it will derive the type from the value provided for you).
Here's the example from earlier:
SQLcmd.Parameters.AddWithValue("#pIDNo", LabelPNumber.Text)

how to store data from vb.net to access a database

I am using an Access database and vb.net 2010. I have created a table in the database with columns for title, datein, dateout and roomnymber. In vb.net 2010 I made a distinguished title = combobox, datein and dateout = DateTimePicker. When I click on F5, an error occurs: INSERT INTO Syntax Error in statement. Here's my code:
Dim sql As String
sql = "INSERT INTO tcekin(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" & "VALUES('" & ComboBox1.Text & _
"','" & txtFirstName.Text & "','" & txtLastName.Text & "','" & txtAddress.Text & "','" & cboCountry.Text & "','" & txtCompany.Text & "','" & txtNumber.Text & _
"','" & dptDateIn.Text & "','" & dptDateOut.Text & "','" & cboRoom.Text & "','" & txtNotes.Text & "')"
cmmd = New OleDbCommand(sql, cnn)
The first problem here is never NEVER NEVER use string concatenation to build your queries like that. Do it like this instead:
Dim sql As String = _
"INSERT INTO tcekin " &_
"(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" &_
"VALUES(?,?,?,?,?,?,?,?,?,?,?)"
cmmd = New OleDbCommand(sql, cnn)
cmmd.Parameters.AddWithValue("Title", Combobox1.Text)
cmmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
''# ...
''# ...
This will also make it easier to spot and avoid syntax errors like the one you're complaining about.