Как сохранить дату в базе данных SQL? - PullRequest
0 голосов
/ 10 сентября 2018

Это мой код:

    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 as Exception "Пожалуйста, введите только цифры".

Есть ли простой способ сохранить дату в базе данных?

1 Ответ

0 голосов
/ 10 сентября 2018

Попробуйте вставить параметр.

 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...