0

我是 VB.NET 和 SQL 的新手。我想更新我的数据库中的记录。我在我的数据库中做了一个假人。

示例值为:ID = 1,name=Cath,age=21

在我用 VB.NET 制作的界面中,我更新了值示例:name = txtName.Text 和 age = txtAge.Text 其中 ID = 1。这是我的主要形式。在我的主表单中,我有“查看”按钮,通知通过单击该按钮,将弹出新表单并查看用户更新的值。该程序没有任何错误,除了当我想再次更新我的SQL中的值时,它会记录但当我再次单击“查看”按钮时,它将显示用户之前输入的内容(运行界面时的第一次更新)。解决方案应该是什么?

这是我的代码:

主窗体:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    SQLConnection.ConnectionString = ServerString
    Try
        If SQLConnection.State = ConnectionState.Closed Then
            SQLConnection.Open()
            MessageBox.Show("Successful connection")
        Else
            'SQLConnection.Close()
            MessageBox.Show("Connection is closed")
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)

    End Try

End Sub

 Public Sub SaveNames(ByRef SQLStatement As String)
    Dim cmd As MySqlCommand = New MySqlCommand
 With cmd
        .CommandText = SQLStatement
        .CommandType = CommandType.Text
        .Connection = SQLConnection
        .ExecuteNonQuery()
    End With

    MsgBox("Successfully Added!")

End Sub

 Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
    Dim date_now As String

    date_now = Format(dtpDate.Value, "yyyy-MM-dd")

    Dim SQLStatement As String = "UPDATE people SET name='" & txtName.Text & "', date ='" & date_now & "'  WHERE 1"
    SaveNames(SQLStatement)
End Sub

表格 2:(查看更新数据的地方)

 Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    SQLConnection.ConnectionString = ServerString
    Try
        If SQLConnection.State = ConnectionState.Closed Then
            SQLConnection.Open()
            '====retrieve / update values in database=============
            Dim SQLStatement As String = "SELECT name, date FROM people"
            ViewInfos(SQLStatement)
        Else
            'SQLConnection.Close()
            MessageBox.Show("Connection is closed")
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)

    End Try
End Sub

 Public Sub ViewInfos(ByRef SQLStatement As String)
    Dim cmd As MySqlCommand = New MySqlCommand

    With cmd
        .CommandText = SQLStatement
        .CommandType = CommandType.Text
        .Connection = SQLConnection
        .ExecuteNonQuery()

    End With
    '--read the records in database in phpmyadmin gui---
    Dim myReader As MySqlDataReader = cmd.ExecuteReader

    If myReader.Read Then
        lblName.Text = myReader.GetString(0)
        lblDate.Text = myReader.GetString(1)

    End If

    myReader.Close()
    MsgBox("Records Successfully Retrieved")

End Sub

任何帮助,将不胜感激。谢谢!

4

2 回答 2

0

从 ViewInfos() 方法中取出 .ExecuteNonQuery() 。

通过变量而不是通过表单名称引用您的表单:

Dim myForm as New Form2()
myForm.Show()
于 2012-07-27T19:15:20.023 回答
0

当您更新 sql 时,您的连接字符串处于打开状态,因此当您尝试检索数据时,您的条件会关闭连接而不读取数据或更新您的文本框。

于 2012-07-27T18:00:02.840 回答