从VB.Net读取和写入SQL信息

时间:2015-07-27 08:04:28

标签: mysql sql database vb.net

我将我的vb.net项目链接到一个唯一的SQL数据库,该数据库包含预定义的电子邮件地址列表。我的vb表单包含' firstname',' lastname'和'电子邮件'文本框。

如何对vb.net进行编程,以便在“电子邮件”中找到该文字。数据库中的文本框,并将fistname和lastname文本框值添加到与所找到的电子邮件字段相同的行中的相应列中? (填补空白)

到目前为止我的代码:

' Initiate SQL Connection for db4free.net on port: 3306
    MySqlConnection = New MySqlConnection
    MySqlConnection.ConnectionString = "server=db4free.net; Port=3306; user id=username; password=password; database=databasename"
    Try
        MySqlConnection.Open()
    Catch ex As Exception
        MsgBox("The server could not be reached, check that you have internet connectivity and try again.", MsgBoxStyle.Critical, "Connection Error")
    End Try

        --- SQL DATABASE CONNECTION --- '
        Dim Myadaptor As New MySqlDataAdapter
        Dim sqlquery = "SELECT * FROM registration WHERE email='" & emailTextBox.Text & "';"
        Dim command As New MySqlCommand
        command.Connection = MySqlConnection
        command.CommandText = sqlquery
        Myadaptor.SelectCommand = command
        Dim Mydata As MySqlDataReader
        Mydata = command.ExecuteReader

        ' SQL Entry Validation
        If Mydata.HasRows = 0 Then
            MsgBox("Please enter a valid E-Mail address", MsgBoxStyle.Critical, "Invalid Details")
        Else
           --- THE ANSWER TO MY QUESTION (write firstname and lastname into row based on email) ---

提前谢谢,(我刚开始学习SQL)。

1 个答案:

答案 0 :(得分:0)

你想要做这样的事情:

If Mydata.HasRows = 0 Then
    MsgBox("Please enter a valid E-Mail address", MsgBoxStyle.Critical, "Invalid Details")
    Mydata.Close()
Else
    Mydata.Close()
    Dim command As New MySqlCommand
    command.Connection = MySqlConnection
    command.ConnectionText = "UPDATE `registration` SET `firstname` = @firstname,`lastname` = @lastname WHERE `email` = @email"
    command.Prepare()
    command.Parameters.AddWithValue("@firstname", firstnameTextBox.Text)
    command.Parameters.AddWithValue("@lastname", lastnameTextBox.Text)
    command.Parameters.AddWithValue("@email", emailTextBox.Text)
    command.ExecuteNonQuery()
End If

您可能需要调整SQL或UI元素的引用以匹配您的设置。

我还将参数绑定到SQL中,而不是通过连接参数来创建字符串,以防止SQL Injection