2014-01-14 169 views
-1

我在直接將數據保存到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 
+2

,什麼是您遇到的錯誤?您需要提供至少*部分*信息。 (提示:你在Catch塊中顯式*忽略*異常,異常包含非常有用的信息,不應該被忽略。系統很可能試圖告訴你到底發生了什麼錯誤,而你只是沒有聽。) – David

+0

沒有看到任何東西給我一個線索。作爲一個PS你不需要關閉連接,並且該catch塊很好調皮... –

+0

沒有它你會得到一個空引用異常,我認爲,給定蒂姆爵士發現了什麼。這就是爲什麼嘗試Catch結束是皺眉... –

回答

2

我認爲問題是,你不分配ConnectionCommand。您可以使用constructorproperty

Dim cmd As New OleDbCommand 
cmd.Connection = dbConnection 
cmd.CommandText = "INSERT INTO Log-In(Username, [Password]) VALUES (@user, @pass)" 
+1

好吧,發現先生 –

+0

謝謝你的答案先生,但程序仍然無法正常工作。 – user3195853

+0

@ user3195853:刪除空的catch塊後發生了什麼?下一個錯誤是什麼?空的catch塊是一種代碼氣味,因爲它們隱藏了重要的信息......但不是來自用戶的重要信息。 –

相關問題