title: VB.NET updating SQL Database Command
body: <p>I am building an asp.net web application using vb and .net 2.0.  I have a class that handles an object and all its attributes.  This class correctly handles reading, creating, and deleting from the database.  However, it will not update.  I took the update script directly from the Microsoft SQL database, but I cannot figure it out.  Here is my SQL command.</p>
  
  <pre><code>saveCommand = "UPDATE [Database].[Table] SET [name] = @name,[content] = @content,[date_updated] = @dateupdated WHERE ref = @ref"
  </code></pre>
  
  <p>This is then being put into...</p>
  
  <pre><code>Dim setCmd As New SqlCommand(saveCommand, sqlConn)
  </code></pre>
  
  <p>And then parameter values are put into it.  It is weird because the "saveCommand" is determined on whether the item already exists (updates) or doesn't (switches to "INSERT INTO" command WHICH WORKS)</p>
  
  <p>More Code</p>
  
  <pre><code>Public Class MyClass()
      #Region Properties
          Public name As String = ""
          Public content As String = ""
          Public date_updated As DateTime = DateTime.Now
      #End Region
  
      Public Sub Save()
      Dim sqlConn As New SqlConnection(sqlConnString)
  
      sqlConn.Open()
  
      Dim saveCommand As String
      If Me.Exists Then
          saveCommand = "UPDATE [Database].[Table] SET [name] = @name,[content] = @content,[date_updated] = @date_updated WHERE ref = @ref"
      Else
          saveCommand = "INSERT INTO [Database].[Table] ([name],[content],[date_updated],[ref]) VALUES(@name,@content,@date_updated,@ref)"
      End If
  
      Dim setCmd As New SqlCommand(saveCommand, sqlConn)
      setCmd.Parameters.Add("@name", Data.SqlDbType.VarChar).Value = Me.name
      setCmd.Parameters.Add("@content", Data.SqlDbType.VarChar).Value = Me.content
      setCmd.Parameters.Add("@date_updated", Data.SqlDbType.DateTime).Value = Me.date_updated
  
      If Me.Exists Then
          setCmd.Parameters.Add("@ref", Data.SqlDbType.Int).Value = Me.ID
      Else
          Dim countCmd As New SqlCommand("SELECT COUNT(*) FROM [DWM-DataSQL].[dbo].[biglots]", sqlConn)
          Me.ID = countCmd.ExecuteScalar() + 1
          setCmd.Parameters.Add("@ref", Data.SqlDbType.Int).Value = Me.ID
          Me.Exists = True
      End If
  
      setCmd.ExecuteNonQuery()
      sqlConn.Close()
      sqlConn.Dispose()
  End Sub
  
  Public Sub New()
  End Sub
  
  Public Sub New(ByVal num As Integer)
      Me.ID = num
  End Sub
  
  End Class
  </code></pre>
  
  <p>This is being called upon by</p>
  
  <pre><code>myObj = New BLL.MyClass(ref)
  
  'When form is submitted
  Public Sub submitForm(ByVal sender As Object, ByVal e As System.EventArgs)
     myObj.name = tbName.Text
     myObj.content = tbcontent.Text
     myObj.Save()
  End Sub
  </code></pre>