简体   繁体   中英

VB.NET updating SQL Database Command

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.

saveCommand = "UPDATE [Database].[Table] SET [name] = @name,[content] = @content,[date_updated] = @dateupdated WHERE ref = @ref"

This is then being put into...

Dim setCmd As New SqlCommand(saveCommand, sqlConn)

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)

More 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

This is being called upon by

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

I figured it out. It was somehow calling upon the read() function RIGHT before the save() function so it replaced all the values. Thanks Anyway

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM