[英]How to insert a date into SQL Server using vb.net
This is my code that will insert data into a datagridview first then into database. 这是我的代码,它将先将数据插入datagridview,然后再插入数据库。
When I run the code, I get the error 运行代码时,出现错误
operand type clash bit is incompatible with date 操作数类型冲突位与日期不兼容
Can anyone help me? 谁能帮我?
Thanks in advance 提前致谢
populate(txtRejectID.Text, comboBoxCardType.Text, txtEmbossName.Text, txt6CardNum.Text, txt4CardNum.Text, txtQuantity.Text, comboBoxErrorDesc.Text, embossDate.Text, txtStatus.Text)
For Each row As DataGridViewRow In DataGridView1.Rows
Dim query As String = "INSERT INTO dbo.RejectCard VALUES (@RejectID, @Card_Type, @Emboss_Name, @Card_Number, @Quantity, @Error_Description, @Emboss_Date, @Status)"
Using conn As New SqlConnection(connString)
Using cmd As New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("@RejectID", row.Cells("rejectid").Value)
cmd.Parameters.AddWithValue("@Card_Type", row.Cells("cardtype").Value)
cmd.Parameters.AddWithValue("@Emboss_Name", row.Cells("embossname").Value)
cmd.Parameters.AddWithValue("@Card_Number", row.Cells("cardnumber").Value)
cmd.Parameters.AddWithValue("@Quantity", row.Cells("quantity").Value)
cmd.Parameters.AddWithValue("@Error_Description", row.Cells("errordescription").Value)
cmd.Parameters.AddWithValue("@Emboss_Date", row.Cells("emboss_Date").Value = embossDate.Value.Date.ToString("dd/MM/yyyy"))
cmd.Parameters.AddWithValue("@Status", row.Cells("status").Value)
Try
conn.Open()
cmd.Connection = conn
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
conn.Close()
End Try
End Using
End Using
Next
MessageBox.Show("Records inserted.")
End Sub
You insert dates exactly the same way as you insert anything else. 您插入日期的方式与插入其他日期的方式完全相同。 The problem is that you're not inserting a Date
. 问题是您没有插入Date
。 You're inserting a Boolean
. 您正在插入Boolean
。 Look at your code. 查看您的代码。 This is the value your inserting: 这是您插入的值:
row.Cells("emboss_Date").Value = embossDate.Value.Date.ToString("dd/MM/yyyy")
That's an equality comparison. 这是一个平等的比较。 The result of an equality comparison is always a Boolean
, ie True
if the values are equal and False
if they're not. 相等比较的结果始终为Boolean
,即,如果值相等则为True
否则为False
。 If you want to insert a Date
then provide a Date
, not a comparison between a value from a grid row and a String
. 如果要插入Date
提供Date
,而不是网格行中的值与String
之间的比较。
Why aren't you just doing for that parameter exactly what you're doing for all the rest? 您为什么不仅仅为该参数做所有其余操作? You clearly think you're achieving something there but I can assure you that you're not. 您显然认为自己在这里取得了成就,但是我可以向您保证,您没有做到。 If what you're trying to do is drop the time from your DateTime
value then you do that by getting the Date
property, not by converting the Date
to a String
. 如果您要执行的操作是从DateTime
值中删除时间,则可以通过获取Date
属性,而不是通过将Date
转换为String
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.