2014-01-05 133 views
0

我正在使用SQL Server,我創建了一個程序來向數據庫添加記錄。但是,數據庫的出生日期字段未被接受。SQL日期格式

在服務器端,數據類型是MS Express SQL Server上的'Date',應該是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") & "'," & _ 

我知道這將是一些非常愚蠢的,但我新望編程。

+2

不要使用瓦爾 - 它是兼容半烤實現。使用Date.Parse,Date.TryParse或Convert.ToDateTime將來會爲您節省很多麻煩。 – Plutonix

回答

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))