如何将日期保存到sql数据库?

tktrz96b  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(415)

这是我的密码:

Dim d As DateTime = DateTime.Now.ToString("MM/dd/yyyy")
    d = txtDate.Text
    Try
        Dim sql = "SELECT Date FROM tblTeacherInfo WHERE Date = '" & txtDate.Text & "'"
        con = connectDB()

        con.Open()

        mycommand = New SqlCommand(sql, con)
        Dim dr As SqlDataReader = mycommand.ExecuteReader
        If dr.Read = True Then
            Try
                If txtReceived.TextLength < 8 Then
                    MsgBox("RFID # should be at least 8 characters in length.", MsgBoxStyle.Critical, "String Size Specification")
                    con.Close()
                Else
                    con.Close()
                    con.Open()
                    mycommand = New SqlCommand("insert into tblTeacherInfo (Date) values ('" & txtDate.Text & "')", con)
                    mycommand.ExecuteNonQuery()
                    MsgBox("New Patron added to the database.", MsgBoxStyle.Information, "CIETI - Information System")
                    ds.Tables("tblTeacherInfo").Rows.Clear()
                    con.Close()
                End If
            Catch ex As Exception
                MsgBox("Data not save.", MsgBoxStyle.Information, "CIETI - Information System")
                con.Close()
                Exit Sub
            End Try
        Else
            MsgBox("Name Already exist", MsgBoxStyle.Critical, "CIETI - Information System")
            ds.Tables("tblTeacherInfo").Rows.Clear()
            'Exit Sub
        End If
    Catch ex As Exception
        MsgBox("Please enter numbers only", MsgBoxStyle.Information, "CIETI - Information System")
        Exit Sub
    End Try

    If con.State <> ConnectionState.Closed Then
        con.Close()
    End If

我保存时出错 Date ,当我运行这个时,它总是转到最后一部分
catch ex作为例外“请仅输入数字”。
有没有简单的方法把日期保存到数据库里?

svgewumm

svgewumm1#

尝试插入参数。

mycommand = New SqlCommand("insert into tblTeacherInfo [(Date)] values (@Date)", con)

 mycommand.Parameters.Add(New SqlParameter With {.ParameterName = "@Date", .SqlDbType = SqlDbType.DateTime, .Value = txtDate.Text})

或者尝试添加一些
Square Brackets [] 为了你,因为 Date 是sql中的保留字。

mycommand = New SqlCommand("INSERT INTO tblTeacherInfo [(Date)] values ('" & txtDate.Text & "')", con)

相关问题