SQL日期格式

时间:2014-01-05 21:14:23

标签: sql-server vb.net

我正在使用SQL Server,我正在创建一个程序来向数据库添加记录。但是,不接受数据库的出生日期字段。

在服务器端,数据类型为MS Express SQL Server上的“日期”,应为YYYY-MM-DD。但是,当尝试从程序“上传”新记录时,日期将被拒绝。我知道这取决于我如何格式化它们,特别是我知道它只是两行代码;但我不能顺利!

  SQL = "Insert into PersonsA(Members_ID," & _
          "Gamer_Tag," & _
          "Screenname," & _
          "First_Name," & _
          "Last_Name," & _
          "DoB," & _
          "E_Mail_Address," & _
          "Position," & _
          "U_G_Studio," & _
          "Cautions," & _
          "Record," & _
          "Event_Attendance," & _
          "Member_Status) values('" & Me.midtxt.Text.Trim & "'," & _
          "'" & Me.gttxt.Text.Trim & "'," & _
          "'" & Me.sntxt.Text.Trim & "'," & _
          "'" & Me.fntxt.Text.Trim & "'," & _
          "'" & Me.lntxt.Text.Trim & "'," & _
          "" & Val(Me.dobtxt.Text) & "" & _ 'THIS IS THE DATES OF BIRTHS
          "'" & Format(Me.dobtxt.Text, "YYYY-MM-DD") & "'," & _ 'THIS IS FORMATTING
          "'" & Me.emailtxt.Text.Trim & "'," & _
          "'" & Me.teamptxt.Text.Trim & "'," & _
          "'" & Me.ugptxt.Text.Trim & "'," & _
          "'" & Me.ugctxt.Text.Trim & "'," & _
          "'" & Me.recordtxt.Text.Trim & "'," & _
          "'" & Me.eventatxt.Text.Trim & "'," & _
          "'" & Me.Mstattxt.Text.Trim & "')"

所以你可以看到我遇到麻烦的两条线是:

    "" & Val(Me.dobtxt.Text) & "" & _ 
   "'" & Format(Me.dobtxt.Text, "YYYY-MM-DD") & "'," & _ 

我知道这将是非常愚蠢的事情,但我对编程很新。

1 个答案:

答案 0 :(得分:3)

拒绝您的命令字符串并开始使用SqlParameter

Dim conn As New SqlConnection("conStr")
Dim cmd As SqlCommand = conn.CreateCommand()

cmd.CommandText = "INSERT INTO [PersonsA] ([Members_ID], [Gamer_Tag]) VALUES (@Members_ID, @Gamer_Tag);"
cmd.Parameters.AddWithValue("@Members_ID", Me.midtxt.Text.Trim) '<- If Int type change to: Integer.Parse(Me.midtxt.Text.Trim)
cmd.Parameters.AddWithValue("@Gamer_Tag", Me.gttxt.Text.Trim)

conn.Open()
cmd.ExecuteNonQuery()

日期列示例:

cmd.Parameters.AddWithValue("@MY_DATE_PARAM", Date.Parse(Me.dateTextBox.Text.Trim))