Vb.net 如果为true,则选择mysql,然后选择update,否则选择insert

Vb.net 如果为true,则选择mysql,然后选择update,否则选择insert,vb.net,sql-server-2008,select,if-statement,Vb.net,Sql Server 2008,Select,If Statement,我需要检查ID是否已经在数据库中,如果是真的:更新值经度、纬度、时间戳。如果没有,则在数据库中插入所有 我现在的脚本是: <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SqlClient"%> <%@ Import Namespace="System.Reflection"%> <%@ Page Language="VB" %> <

我需要检查ID是否已经在数据库中,如果是真的:更新值经度、纬度、时间戳。如果没有,则在数据库中插入所有

我现在的脚本是:

<%@ Import Namespace="System.Data"%>   
<%@ Import Namespace="System.Data.SqlClient"%>   
<%@ Import Namespace="System.Reflection"%>
<%@ Page Language="VB" %>  
<script runat="server">  


    Dim Con As New SqlConnection
    Dim Cmd As New SqlCommand
    Dim SQLCommand As String = ""
    Dim Reader As SqlDataReader

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not String.IsNullOrEmpty(Request.QueryString("data")) Then
        Dim data As String = Request.QueryString("data")

        Dim myObj As New MyObject
        Dim properties() As PropertyInfo = myObj.GetType().GetProperties()
        Dim values() As String = Server.UrlDecode(data).Replace("{", "").Replace("}", "").Replace(""":""", """=""").Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries)
        For Each value As String In values
            Dim keyValue() As String = value.Split(New Char() {"="}, StringSplitOptions.RemoveEmptyEntries)
            For Each prop As PropertyInfo In properties
                If prop.Name.ToLower = keyValue(0).ToLower.Replace("""", "") Then
                    prop.SetValue(myObj, keyValue(1).Replace("""", ""), Nothing)
                End If
            Next
        Next

        myObj.Save()
        lblText1.Text = String.Format("ID: {0}", myObj.ID)
        lblText2.Text = String.Format("Longitude: {0}", myObj.Longitude)
        lblText3.Text = String.Format("Latitude: {0}", myObj.Latitude)
        lblText4.Text = String.Format("Timestamp: {0}", myObj.Timestamp)


'cmd.Parameters.AddWithValue("@ID", ID)
'cmd.Parameters.AddWithValue("@Longitude", Longitude)
'cmd.Parameters.AddWithValue("@Latitude", Latitude)
'cmd.Parameters.AddWithValue("@Timestamp", Timestamp)

'Con.ConnectionString = "Data Source=sr04011389\sql02;Initial Catalog=LocatieBepaling_Ontw;Integrated Security=True"
    'Cmd.Connection = Con
    'Con.Open()

   '     Cmd.CommandText = "INSERT INTO dbo_Locatie(id, Longitude, Latitude, Timestamp) VALUES (1234, 4567, 789, 12-12-2012)"


' Reader = Cmd.ExecuteReader

 '        Reader.Close()
  '       Con.Close()
 '      Con.Dispose()



    End If

End Sub
'Dim values() As String = Server.UrlDecode(data).Replace("{", "").Replace("}", "").Replace(""":""", """=""").Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries)  For Each value As String In values 


Public Class MyObject
    Private _ID As String
    Private _Longitude As String
    Private _Latitude As String
    Private _Timestamp As String


    Public Property ID As String
        Get
            Return _ID
        End Get
        Set(value As String)
            _ID = value
        End Set
    End Property


    Public Property Longitude As String
        Get
            Return _Longitude
        End Get
        Set(value As String)
            _Longitude = value
        End Set
    End Property


    Public Property Latitude As String
        Get
            Return _Latitude
        End Get
        Set(value As String)
            _Latitude = value
        End Set
    End Property


    Public Property Timestamp As String
        Get
            Return _Timestamp
        End Get
        Set(value As String)
            _Timestamp = value
        End Set
    End Property


    Public Function Save() As Boolean
 Return True
    Using objConn As New SqlConnection("Server=sr04011389\sql02;database=LocatieBepaling_Ontw;Trusted_Connection=yes;Max Pool Size=400;Connect Timeout=600;")
      Try

            Dim cmd As New SqlCommand("csp_save_my_object")
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@ID", ID)
            cmd.Parameters.AddWithValue("@Longitude", Longitude)
            cmd.Parameters.AddWithValue("@Latitude", Latitude)
            cmd.Parameters.AddWithValue("@Timestamp", Timestamp)
           Return cmd.ExecuteNonQuery() > 0
        Catch ex As Exception
           Return False
       End Try
    End Using

    End Function


    Public Function SaveWithoutSP() As Boolean
       Return True
        Using Con As New SqlConnection("Server=sr04011389\sql02;database=LocatieBepaling_Ontw;Trusted_Connection=yes;Max Pool Size=400;Connect Timeout=600;")
            Try
               Con.Open()
               Dim cmd As New SqlCommand("UPDATE dbo_Locatie SET (Longitude = @Longitude, Latitude = @Latitude,Timestamp = @Timestamp) WHERE id=@ID IF @@ROWCOUNT=0 INSERT INTO locatie VALUES (@ID, @Longitude, @Latitude, @Timestamp)")
              cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("@ID", ID)
                cmd.Parameters.AddWithValue("@Longitude", Longitude)
                cmd.Parameters.AddWithValue("@Latitude", Latitude)
                 cmd.Parameters.AddWithValue("@Timestamp", Timestamp)
                Return cmd.ExecuteNonQuery() > 0
            Catch ex As Exception
                Return False

            End Try
        End Using
    End Function
End Class



 'Sub Page_UnLoad()   
 'objConn.Close()   
 'objConn = Nothing  
 'End Sub  

 </script>  

 <html>   
 <head>   
 <title>TracknTrace</title>   
 </head>   
 <body>   
 <form id="form1" runat="server">   
 <asp:Label id="lblText" runat="server"></asp:Label> 
 <br><asp:Label id="lblText1" runat="server"></asp:Label> </br>
 <br><asp:Label id="lblText2" runat="server"></asp:Label> </br> 
 <br><asp:Label id="lblText3" runat="server"></asp:Label> </br>
 <br><asp:Label id="lblText4" runat="server"></asp:Label> </br>
 </form> 

您可以尝试在重复密钥更新类型的查询中使用
插入
。其工作方式是,如果记录不存在,则插入该记录。如果是,则更新值

INSERT INTO locatie (...) VALUES (...)
ON DUPLICATE KEY UPDATE longitude = '$longitude', ...
这就是您要求的吗???

编辑:用于SQL Server

要使用的sql文本如下所示

UPDATE locatie SET (longitude = @longitude, 
                    latitude = @latitude,
                    timestamp = @timestamp) 
WHERE ID=@ID 
IF @@ROWCOUNT=0 
    INSERT INTO locatie VALUES (@ID, @longitude, @latitude, @timestamp)
假设ID字段不是autoicrement列,timestamp不是timestamp数据类型列

如果将上面的文本另存为storedprocedure,则在VB.NET中将所有内容写入字符串中,但应在WHERE ID=@ID后面插入分号

  Dim cmd As New SqlCommand("UPDATE dbo_Locatie SET (Longitude = @Longitude, " + 
                            "Latitude = @Latitude,Timestamp = @Timestamp) WHERE id=@ID; " + 
                            "IF @@ROWCOUNT=0 INSERT INTO locatie " + 
                            "VALUES (@ID, @Longitude, @Latitude, @Timestamp)")

作为补充:与其捕获异常而不对异常执行任何操作,不如让异常抛出。错误消息可能会暴露出来。

我现在正在使用vb.net。我需要将php转换为vb.net,但我也不太确定我的插入现在是否有效。。因为我注释了obj.conn close,并且没有错误,givenCatch ex As Exception Return False,所以我没有收到任何错误,所以我想它现在应该可以使用vb.net工作了。我需要将php转换为vb.net,但我也不太确定我的插入现在是否有效。。因为我注释了obj.conn close,并且没有错误,所以givenSQL在这里可以工作。我试着用一个简单的aspx文件来测试连接,你是在使用MySql还是Sql Server?您已经用MySql标记了您的问题。在这种情况下,您能否显示“csp\u save\u my\u object”的代码,并告诉我ID列是否为自动增量列?。如果ID不是自动增量列,则没有StoredProcedure的代码只能插入行。此外,时间戳是Sql Server的数据类型保留字,如果用于定义列的数据类型,则不能像自动增量列那样更新该列。所有字段和值都是字符串类型。我不太清楚如何显示csp_save_my_对象的代码。我使用的所有代码都在本文中。要查找使用Sql Management Studio连接到数据库的StoredProcess代码,请在可编程性节点下的存储过程中查找csp_save_my_对象。单击鼠标右键并选择“修改”。您可以在右侧窗格中看到代码,
UPDATE locatie SET (longitude = @longitude, 
                    latitude = @latitude,
                    timestamp = @timestamp) 
WHERE ID=@ID 
IF @@ROWCOUNT=0 
    INSERT INTO locatie VALUES (@ID, @longitude, @latitude, @timestamp)
  Dim cmd As New SqlCommand("UPDATE dbo_Locatie SET (Longitude = @Longitude, " + 
                            "Latitude = @Latitude,Timestamp = @Timestamp) WHERE id=@ID; " + 
                            "IF @@ROWCOUNT=0 INSERT INTO locatie " + 
                            "VALUES (@ID, @Longitude, @Latitude, @Timestamp)")