我在直接將數據保存到Microsoft Access數據庫時遇到了Visual Basic.NET代碼中的問題。這裏是我試圖完成我的問題代碼:如何將數據直接保存到vb.net的數據庫中
Imports System.Data.OleDb
Public Class Form1
Dim cnn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\ching13\Desktop\watta1.mdb"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Using dbConnection = New OleDbConnection(cnn)
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Try
dbConnection.Open()
Dim cmd As New OleDbCommand
cmd.CommandText = "INSERT INTO Log-In(Username, [Password]) VALUES (@user, @pass)"
cmd.Parameters.Add(New OleDbParameter("@user", DbType.String))
cmd.Parameters.Add(New OleDbParameter("@pass", DbType.String))
cmd.Prepare()
cmd.Parameters("@user").Value = TextBox1.Text
cmd.Parameters("@pass").Value = TextBox2.Text
cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
dbConnection.Close()
End Try
MessageBox.Show("Data Saved")
TextBox1.Text = ""
TextBox2.Text = ""
End Using
End Sub
End Class
這是我修改後的Visual Basic代碼:
Imports System.Data.OleDb
Public Class Form1
Dim cnn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ching13\Desktop\watta2.accdb"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Using dbConnection = New OleDbConnection(cnn)
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
dbConnection.Open()
Dim cmd As New OleDbCommand
cmd.Connection = dbConnection
cmd.CommandText = "INSERT INTO Log-In(Username, [Password]) VALUES (@user, @pass)"
cmd.Parameters.Add(New OleDbParameter("@user", DbType.String))
cmd.Parameters.Add(New OleDbParameter("@pass", DbType.String))
cmd.Prepare()
cmd.Parameters("@user").Value = TextBox1.Text
cmd.Parameters("@pass").Value = TextBox2.Text
cmd.ExecuteNonQuery()
dbConnection.Close()
MessageBox.Show("Data Saved")
TextBox1.Text = ""
TextBox2.Text = ""
End Using
End Sub
End Class
,什麼是您遇到的錯誤?您需要提供至少*部分*信息。 (提示:你在Catch塊中顯式*忽略*異常,異常包含非常有用的信息,不應該被忽略。系統很可能試圖告訴你到底發生了什麼錯誤,而你只是沒有聽。) – David
沒有看到任何東西給我一個線索。作爲一個PS你不需要關閉連接,並且該catch塊很好調皮... –
沒有它你會得到一個空引用異常,我認爲,給定蒂姆爵士發現了什麼。這就是爲什麼嘗試Catch結束是皺眉... –