将日期值存储到MySQL数据库时出错

时间:2011-09-08 08:42:22

标签: mysql sql vb.net

我曾尝试过几种类型的日期格式,然而,我仍然无法做到这一点。

以下是编写的编码

Dim serverDate As String = Format(Now(), "DD-MM-YYYY")
strNew &= "INSERT INTO Staff ("
            strNew &= "full_name"
            strNew &= ", login_id"
            strNew &= ", passwd"
            strNew &= ", last_update"
            strNew &= ") VALUES ("
            strNew &= "'" & txt_Name.Text & "'"
            strNew &= ", '" & txt_Login.Text & "'"
            strNew &= ", '" & txt_Password.Text & "'"
            strNew &= ", (STR_TO_DATE('" & serverDate & "', '%d-%m-%Y'))"
            strNew &= ")"

知道我错过了什么?..非常感谢帮助..

编辑#1: 忘了添加错误信息
“日期时间值不正确:'DD-09-YYYY'表示函数str_to_date”

1 个答案:

答案 0 :(得分:0)

您正在使用硬编码 sql字符串,因此您需要使用yyyy-MM-dd格式日期。

Dim serverDate As String = DateTime.Now.ToString("yyyy-MM-dd")

strNew &= "INSERT INTO Staff ("
            strNew &= "full_name"
            strNew &= ", login_id"
            strNew &= ", passwd"
            strNew &= ", last_update"
            strNew &= ") VALUES ("
            strNew &= "'" & txt_Name.Text & "'"
            strNew &= ", '" & txt_Login.Text & "'"
            strNew &= ", '" & txt_Password.Text & "'"
            strNew &= ", '" & serverDate & "'"
            strNew &= ")

编辑:

  

@BlurrieBlue:   忘了添加错误消息“不正确的日期时间值   :'DD-09-YYYY'用于函数str_to_date“

是的格式不正确。它应该是

Format(Now(), "dd-MM-yyyy")

看看这段代码片段

cmd=new MySqlCommand()
cmd.Connection=cn
cmd.CommandText="INSERT INTO Staff (?full_name,?login_id,?passwd,?last_update)"
cmd.Parameters.Add("?full_name", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value =txt_Name.Text
cmd.Parameters.Add("?login_id", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value =txt_Login.Text
cmd.Parameters.Add("?passwd", MySql.Data.MySqlClient.MySqlDbType.VarChar).Value =txt_Password.Text
cmd.Parameters.Add("?last_update", MySql.Data.MySqlClient.MySqlDbType.DateTime).Value =DateTime.Now

cn.Open()
cmd.ExecuteNonQuery()
cn.Close()

偏离主题:不要使用hard-coded sql字符串。使用参数化的sql语句。