我是VB.NET和SQL中的新成員。我想更新我的數據庫中的記錄。我在我的數據庫中做了一個假人。更新vb.net中的SQL語句
實施例中的值是:ID = 1,姓名=蛋白酶,年齡= 21
以我接口在VB.NET製成,我更新的值例如:名稱= txtName.Text和年齡= txtAge.Text其中ID = 1。這是我的主要形式。在我的主窗體中,我有「查看」按鈕,通知單擊該按鈕,將彈出新窗體,並查看用戶更新的值。該程序沒有任何錯誤,只是當我想再次更新SQL中的值時,它會記錄BUT,當我再次單擊「查看」按鈕時,它會顯示以前由用戶輸入的內容(運行界面時的第一次更新)。應該是什麼解決方案?
這是我的代碼:
的MainForm:
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
任何幫助,將不勝感激。謝謝!
只是一個旁註:總是緊密聯繫立即(最好使用語句)。連接池實際上不會關閉它,但將其標記爲_usable_。 – 2012-07-27 16:42:14
我認爲它應該是Dim SQLStatement As String =「UPDATE people SET name ='」&txtName.Text&「',date ='」&date_now&''WHERE ID = 1「 – Mithrandir 2012-07-27 16:44:33
Noooo,不要連接字符串做sql語句! – King 2012-07-27 16:54:13