SQL更新查询VB ASP

时间:2014-04-03 18:30:01

标签: asp.net sql vb.net

我试图在SQL Server数据库中通过VB与ASP.net进行更新查询

下面的这段代码更新了具有相同值的所有记录。我希望它只更新一条记录,具体取决于"电子邮件"会话变量。

Dim cmdstring As String = "UPDATE [Customer] SET card_type=@CARDTYPE"

    Email = Session("email")
    ', Card_Number, Expiry_Date, Security_Number, Name_On_Card) Values (@CARDTYPE, @CARDNUMBER, @EXPIRYDATE, @SECURITYNUMBER, @NAMEONCARD)"

    conn = New SqlConnection("data source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\UniversityClothing.mdf;Integrated Security=True;User Instance=True")
    cmd = New SqlCommand(cmdstring, conn)

    cmd.Parameters.AddWithValue("@CARDTYPE", cardtype)
    cmd.Parameters.AddWithValue("@CARDNUMBER", cardnumber)
    cmd.Parameters.AddWithValue("@EXPIRYDATE", expirydate)
    cmd.Parameters.AddWithValue("@SECURITYNUMBER", securitynumber)
    cmd.Parameters.AddWithValue("@NAMEONCARD", nameoncard)

    conn.Open()

    cmd.ExecuteNonQuery()

    conn.Close()

2 个答案:

答案 0 :(得分:1)

这样做:

Using conn As New SqlConnection("data source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\UniversityClothing.mdf;Integrated Security=True;User Instance=True"), _
      cmd As New SqlCommand("UPDATE [Customer] SET card_type=@CARDTYPE WHERE email = @Email", conn)

    cmd.Parameters.AddWithValue("@CARDTYPE", cardtype)
    cmd.Parameters.AddWithValue("@Email", Session("email"))

    conn.Open()
    cmd.ExecuteNonQuery()
End Using

另请注意,我真的不喜欢AddWithValue()方法。它可能导致严重的性能问题。

答案 1 :(得分:0)

您需要添加WHERE子句。例如:

Dim cmdstring As String = "UPDATE [Customer] SET card_type=@CARDTYPE, Card_Number=@CARDNUMBER, Expiry_Date=@EXPIRYDATE, Security_Number=@SECURITYNUMBER, Name_On_Card=@NAMEONCARD WHERE Email=@EMAIL)"
Email = Session("email")

conn = New SqlConnection("data source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\UniversityClothing.mdf;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdstring, conn)
cmd.Parameters.AddWithValue("@CARDTYPE", cardtype)
cmd.Parameters.AddWithValue("@CARDNUMBER", cardnumber)
cmd.Parameters.AddWithValue("@EXPIRYDATE", expirydate)
cmd.Parameters.AddWithValue("@SECURITYNUMBER", securitynumber)
cmd.Parameters.AddWithValue("@NAMEONCARD", nameoncard)
cmd.Parameters.AddWithValue("@EMAIL", Email)

conn.Open()

cmd.ExecuteNonQuery()

conn.Close()

注意以下内容:

  1. 根据PCI规定,您不应存储安全号码,并且应该 为您的卡号做适当的加密
  2. 我假设您已经验证了所有字段以防止SQL注入