我是visual basic的新手,现在我正在研究如何将csv文件导入数据库。我有这个代码导入csv文件来访问数据库,但我不断收到此错误:
'txtFile' is not declared. It may be inaccessible due to its protection level
这是代码。
Imports System.Data.OleDb
Imports System.Threading
Imports System.Windows
Imports System.Collections
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim cnAccess As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source=" & Application.StartupPath & "C:\Users\vissia18\Desktop\ReportDB2.accdb;")
Dim op1 As New OpenFileDialog
op1.ShowDialog()
txtFile.Text = op1.FileName
Dim QryInsert As String = "", QryCreate As String = ""
Dim i As Integer
Dim cmd As New OleDbCommand
Dim Fnm As String = txtFile.Text
Dim s1 As String
Dim s2(5) As String
Dim freader As New IO.StreamReader(Fnm, False)
cmd.Connection = cnAccess
cnAccess.Open()
While (freader.EndOfStream = False)
s1 = freader.ReadLine
s2 = s1.Split(",")
QryInsert = "Insert Into Report Values (" & s2(0) & ",'" & s2(1) & "'," & s2(2) & ")"
cmd.CommandText = QryInsert
cmd.ExecuteNonQuery()
End While
MsgBox("Data Imported Successfully")
cnAccess.Close()
End Sub
End Class
如果我在其他地方出错了,请纠正我。任何帮助将非常感谢。
答案 0 :(得分:1)
txtFile
。你需要在使用它们之前声明变量。
尝试替换
txtFile.Text = op1.FileName
[....]
Dim Fnm As String = txtFile.Text
与
Dim txtFile as String = op1.FileName
[....]
Dim Fnm As String = txtFile