0

我需要检查 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> 


而我之前使用的 PHP 代码是:

 $result = mysql_query("SELECT * FROM locatie WHERE id='$id'");
 if($result && mysql_num_rows($result)>0){
 {
 $query = "Update locatie 
 SET     longitude = '$longitude',
 latitude = '$latitude',
 timestamp = '$timestamp'
 WHERE id = '$id'";}
 else
 //Als het nummer bekend is

 {
  //Als het een nieuw nummer is
 $query = sprintf("INSERT INTO locatie (id, longitude, latitude, timestamp) VALUES ('% s', '%s', '%s', '%s') ", mysql_real_escape_string($id) , mysql_real_escape_string ($longitude),  mysql_real_escape_string($latitude), mysql_real_escape_string($timestamp));}



 $result = mysql_query($query) or die('Query failed: ' . mysql_error());
 echo "OK";
4

3 回答 3

1

编辑:对于 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 数据类型列。

如果将上述文本保存为存储过程,则在 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)")

作为旁注:与其捕获异常而不对异常做任何事情,不如让异常抛出。错误消息可能会暴露。

于 2012-11-01T09:49:47.953 回答
0

您可以尝试使用一种INSERT ON DUPLICATE KEY UPDATE查询。它的工作方式是如果记录不存在,则插入它。如果是,则更新值。

INSERT INTO locatie (...) VALUES (...)
ON DUPLICATE KEY UPDATE longitude = '$longitude', ...
于 2012-11-01T09:13:46.673 回答
0
INSERT INTO locatie (id, longitude, latitude, timestamp)
ON DUPLICATE KEY UPDATE 
longitude = '$longitude',latitude = '$latitude',timestamp = '$timestamp';

这是你要的吗???

于 2012-11-01T09:16:02.930 回答