【问题标题】:Inserting trouble插入麻烦
【发布时间】:2014-11-21 09:23:54
【问题描述】:

我的数据库“tipical_bd”上有两个表。 一个表“linha”,其中名称具有主键“endereco_ip”,另一个表名为 postos,具有外键“endereco_ip”和变量“ posto_ID”。

在我的数据库中,我无法将“endereco_ip”中的值放入“posto_ID”表中。 主键“endereco_ip”得到正确的值,但我不能把这个值放在表“posto_ID”中以供以后通过搜索参考,有人可以告诉我什么代码错了吗?

Private Sub inserir_Click(sender As Object, e As EventArgs) Handles inserir.Click
    Dim insertip_bd As String = "INSERT INTO linha (endereco_ip) VALUES (@endereco_ip)"
    Dim inserirposto_bd As String = "INSERT INTO posto (postos_id, endereco_ip) VALUES(@posto_id, (SELECT linha.endereco_ip FROM linha WHERE linha.endereco_ip=posto.endereco_ip))"

    Dim connection As New MySqlConnection(myConnectionString)

    Dim command_ip As New MySqlCommand(insertip_bd, connection)
    Dim command_posto As New MySqlCommand(inserirposto_bd, connection)


    If (ipText.Text = "" Or postoText.Text = "") Then
        MessageBox.Show("Não foi inserido nenhum valor")
    Else
        ip_address = CInt(ipText.Text)
        posto = CInt(postoText.Text)

        Try
            connection.Open()
            'ListBox1.Items.Add(". . .")
            command_ip.Parameters.AddWithValue("@endereco_ip", ip_address)
            command_posto.Parameters.AddWithValue("@postos_id", connection)

            command_ip.ExecuteNonQuery()
            command_posto.ExecuteNonQuery()
        Catch ex As Exception
            MessageBox.Show("Erro de ligação", "AVISO!!!")
        End Try

        connection.Close()
        command_ip = Nothing
        command_posto = Nothing
    End If
End Sub

【问题讨论】:

  • 问题:你为什么要做:'"INSERT INTO posto (postos_id, endereco_ip) VALUES(@posto_id, (SELECT linha.endereco_ip FROM linha WHERE linha.endereco_ip=posto.endereco_ip)' 而不仅仅是正在做:“INSERT INTO posto (postos_id, endereco_ip) VALUES(@posto_id, @endereco_ip)”
  • 因为 endereco_ip 它是一个主键,我假装为搜索做了参考。已经尝试按照您提到的方式放置,但值 endere_ip 未出现在 postos 表中。这个想法是在 Table Postos 中编写自动假设的 endereco_ip。

标签: mysql sql vb.net sql-insert


【解决方案1】:

您当前的插入:-

INSERT INTO posto (postos_id, endereco_ip) 
VALUES(@posto_id, (SELECT linha.endereco_ip FROM linha WHERE linha.endereco_ip=posto.endereco_ip))

我通常会写成:-

INSERT INTO posto (postos_id, endereco_ip) 
SELECT @posto_id, linha.endereco_ip 
FROM linha 
WHERE linha.endereco_ip=posto.endereco_ip

这样做对我来说似乎更合乎逻辑,并且使加入的尝试更加明显。

您的 WHERE 子句正在检查 linha.endereco_ip=posto.endereco_ip 但您没有选择/加入 posto 表,因此 posto.endereco 没有价值。

现在我无法确定你想从哪里获取这个值来检查,除非你想检查固定值并使用表中的 id(类似这样):-

INSERT INTO posto (postos_id, linha_id) 
SELECT @posto_id, linha.endereco_ip 
FROM linha 
WHERE linha.endereco_ip=@endereco_ip

【讨论】:

    猜你喜欢
    • 2017-03-01
    • 2014-05-10
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2014-06-28
    • 1970-01-01
    相关资源
    最近更新 更多