我是VB.net(2周)的新用戶,來自PHP背景,我發現它很難。我創建了一個小表單,它應該將一些數據插入到訪問mdb數據庫中。不過,我不斷收到一個錯誤信息:這哪裏錯誤發生我在粘貼代碼概述VB2010數據庫插入查詢拋出異常錯誤
System.Data.OleDb.OleDbException
,並請將哪裏出了問題有人能指出。非常感謝。
Imports System.Data.OleDb
Public Class frmMain
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\domain\storage1.mdb"
Dim cnnOLEDB As New OleDbConnection(strConnectionString)
Dim cmdOLEDB As New OleDbCommand
Dim cmdInsert As New OleDbCommand
Dim cmdUpdate As New OleDbCommand
Dim cmdDelete As New OleDbCommand
Dim cmd As OleDbCommand
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
Dim first, last As String
Dim age As Integer
first = txtFirstName.Text
last = txtLastName.Text
age = txtAge.Text
Dim InsertQuery As String
InsertQuery = "INSERT INTO Details (first,last,age) VALUES ('" & first & "','" & last & "','" & age & "')"
cnnOLEDB.Open()
Dim cmd As OleDbCommand = New OleDbCommand(InsertQuery, cnnOLEDB)
cmd.Parameters.AddWithValue("first", txtFirstName.Text)
cmd.Parameters.AddWithValue("last", txtLastName.Text)
cmd.Parameters.AddWithValue("age", txtAge.Text)
cmd.ExecuteNonQuery() <--- ERROR
cnnOLEDB.Close()
MessageBox.Show("Insert complete.")
End Sub
End Class
感謝您告訴我們錯誤在哪裏,這很有幫助。將來,告訴我們錯誤是什麼。錯誤的類型「System.Data.OleDb.OleDbException」只是沒有什麼幫助,應該有一個錯誤消息說「數據類型不匹配:字符串的類型不能轉換爲數字」或類似的東西那。如果您不確定哪條消息是我正在討論的,請在您的代碼周圍放置TRY/CATCH,然後將ex.ToString()提供給我們。 – Steve
@Steve謝謝關於try/catch的建議。將來會使用。 – user1532468