Having trouble with OleDbConnection - vb.net

I'm working on a program that will go out to an access database, wipe out the records for all 4 of the tables that I specify, before creating a new table in the database that contains all of the data from my Excel "Table of Contents" file. I'm having trouble with the OleDbConnection side of things. It keeps erroring out on the line that contains conn.Open() with the error "Invalid Argument"
My code is as follows:
Private Sub btnAccess_Click(sender As System.Object, e As System.EventArgs) Handles btnAccess.Click
Dim AccessPath As String = ""
Dim com1 As OleDbCommand
Dim com2 As OleDbCommand
Dim com3 As OleDbCommand
Dim com4 As OleDbCommand
Dim DatabaseFile As String = ""
Dim DatabaseFileTitle As String = ""
Dim ExcelFile As String = ""
Dim ExcelFileTitle As String = ""
Dim connect As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelFile & _
";Extended Properties=Excel 12.0;"
OpenFileDialog2.DefaultExt = "*.accdb"
MsgBox("Select the ACCESS FILE from the working directory.", , "BROWSE FOR THE ACCESS DATABASE")
OpenFileDialog2.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog2.Filter = "Access Database (*.accdb)|*.accdb"
OpenFileDialog2.Title = "Select ACCESS DATABASE File."
OpenFileDialog2.ShowDialog()
DatabaseFile = OpenFileDialog2.FileName
DatabaseFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog2.FileName)
OpenFileDialog3.DefaultExt = "*.xlsx"
MsgBox("Select the EXCEL TOC FILE from the working directory.", , "BROWSE FOR THE EXCEL TOC")
OpenFileDialog3.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog3.Filter = "Excel Spreadhseet (*.xlsx)|*.xlsx"
OpenFileDialog3.Title = "Select EXCEL TOC File."
OpenFileDialog3.ShowDialog()
ExcelFile = OpenFileDialog3.FileName
ExcelFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog3.FileName)
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand()
cmd.Connection = conn
cmd.CommandText = "SELECT * INTO [MS Access;Database=" & DatabaseFile & "].[New Table] FROM [Sheet1$]"
conn.Open()
cmd.ExecuteNonQuery()
com1 = New OleDbCommand("delete from tblArtId", conn)
com2 = New OleDbCommand("delete from tblFigure", conn)
com3 = New OleDbCommand("delete from tblSubGroups", conn)
com4 = New OleDbCommand("delete from tblGroups", conn)
com1.ExecuteNonQuery()
com2.ExecuteNonQuery()
com3.ExecuteNonQuery()
com4.ExecuteNonQuery()
conn.Close()
End Using
End Using
MsgBox("Records Deleted")
End Sub

If anyone is curious....my updated code is as follows:
Private Sub btnAccess_Click(sender As System.Object, e As System.EventArgs) Handles btnAccess.Click
Dim AccessPath As String = ""
Dim com1 As OleDbCommand
Dim com2 As OleDbCommand
Dim com3 As OleDbCommand
Dim com4 As OleDbCommand
Dim DatabaseFile As String = ""
Dim DatabaseFileTitle As String = ""
Dim ExcelFile As String = ""
Dim ExcelFileTitle As String = ""
OpenFileDialog2.DefaultExt = "*.accdb"
MsgBox("Select the ACCESS FILE from the working directory.", , "BROWSE FOR THE ACCESS DATABASE")
OpenFileDialog2.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog2.Filter = "Access Database (*.accdb)|*.accdb"
OpenFileDialog2.Title = "Select ACCESS DATABASE File."
OpenFileDialog2.ShowDialog()
DatabaseFile = OpenFileDialog2.FileName
DatabaseFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog2.FileName)
OpenFileDialog3.DefaultExt = "*.xlsx"
MsgBox("Select the EXCEL TOC FILE from the working directory.", , "BROWSE FOR THE EXCEL TOC")
OpenFileDialog3.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog3.Filter = "Excel Spreadhseet (*.xlsx)|*.xlsx"
OpenFileDialog3.Title = "Select EXCEL TOC File."
OpenFileDialog3.ShowDialog()
ExcelFile = OpenFileDialog3.FileName
ExcelFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog3.FileName)
Dim connectExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelFile & _
";Extended Properties=Excel 12.0;"
Dim connectAccess As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabaseFile & ";"
Using connExcel As New OleDbConnection(connectExcel)
Using cmd As New OleDbCommand()
cmd.Connection = connExcel
cmd.CommandText = "SELECT * INTO [MS Access;Database=" & DatabaseFile & "].[New Table] FROM [TOC Output for Excel$]"
connExcel.Open()
cmd.ExecuteNonQuery()
connExcel.Close()
End Using
End Using
Using connAccess As New OleDbConnection(connectAccess)
Using cmdAccess As New OleDbCommand()
com1 = New OleDbCommand("delete from tblArtId", connAccess)
com2 = New OleDbCommand("delete from tblFigure", connAccess)
com3 = New OleDbCommand("delete from tblSubGroups", connAccess)
com4 = New OleDbCommand("delete from tblGroups", connAccess)
connAccess.Open()
com1.ExecuteNonQuery()
com2.ExecuteNonQuery()
com3.ExecuteNonQuery()
com4.ExecuteNonQuery()
connAccess.Close()
End Using
End Using
MsgBox("Staging Table has been created. All Records Deleted from Group, SubGroup, Figure, and ArtID tables")
End Sub

Related

Create table from Excel file

I'm trying to create a temp table on my database from an Excel file uploaded by the user. I cannot understand where is the problem and why Visual Studio is throwing that exception.
Code
Private Sub Excel_Load(ByVal filePath As String)
Dim myConn As SqlConnection
Dim myCmd As SqlCommand
Dim sqlCmd As String
Dim filename As String = Path.GetFileNameWithoutExtension(filePath)
'Setting up Connection'
myConn = New SqlConnection("Server=*****;Database=*****;User ID=*****;Password=*****;Integrated Security=SSPI;")
myConn.Open()
'Create table'
sqlCmd = "CREATE TABLE XlsTemp AS (SELECT * FROM EXCELLINK [" & filename & "$])"
'Execute Query'
myCmd = myConn.CreateCommand()
myCmd.CommandText = sqlCmd
myCmd.ExecuteNonQuery()
myConn.Close()
End Sub
Exception
SqlException: The object name 'EXCELLINK' is not valid.
Peu_UNRAE is my Excel file.
At the end I come up with this solution:
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim fileExcelType As String
//Get the file extension in order to use the propper provider
If IO.Path.GetExtension(fileExcel.ToUpper) = ".XLS" Then
fileExcelType = "Excel 8.0"
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
Else
fileExcelType = "Excel 12.0"
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
End If
//Opening excel connection
MyConnection.Open()
Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection)
MyCommand.TableMappings.Add("Table", " ")
MyCommand.Fill(dt)
//Closing connection
MyConnection.Close()
Remarks:
I used // for the comments because the standar ' was giving some problem here on StackOverflow

cant find Isam installable CSV Files

Hey I am having a problem taking an excel spread sheet and inserting it into a data-grid in Visual Studio 2013 I was wondering if anyone could give me a hand.
Here is the code I have at the moment.
getting the error Could not find installable ISAM only when I have clicked on the csv fle iut works for ll the other files?
OpenFileDialog1.ShowDialog()
Dim filePath As String = OpenFileDialog1.FileName
Dim extension As String = Path.GetExtension(filePath)
Dim header As String = If(rbHeaderYes.Checked, "YES", "NO")
Dim conStr As String, sheetName As String
conStr = String.Empty
Select Case extension
Case ".xls"
'Excel 97-03
conStr = String.Format(Excel03ConString, filePath, header)
Exit Select
Case ".xlsx"
'Excel 07
conStr = String.Format(Excel07ConString, filePath, header)
Exit Select
Case ".csv"
'CSV
conStr = String.Format(ExcelCsv, filePath, header)
Exit Select
End Select
'Get the name of the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
cmd.Connection = con
con.Open()
Dim dtExcelSchema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
sheetName = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
con.Close()
End Using
End Using
'Read Data from the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmd.CommandText = (Convert.ToString("SELECT * From [") & sheetName) + "]"
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
'Populate DataGridView.
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub

Check if value exist in DBF database

I am trying to check if value "IAV-1419" exist in second column (ColName) in database named PROMGL.DBF.
I get this error : No value give for one or more required parameters
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV"
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
I am stuck here, if anyone could please check this code for me.
are you sure that your connectionstring is correct????
Data Source=" & FilePath &
how connection string know the database where it point only to "C:\" i think is missing database name
Another personal suggestion make your code more simple to read in example :
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL", con
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
End Using
End Using

Error "Child list for field [Sheet1$] cannot be created" when loading data from excel to datagridview

I am trying to fill the DataGridView (grvExcelData in this case) with data from an excel file. But I am getting the following error:
"Child list for field [Sheet1$] cannot be created"
Below is my code fragment where I am trying to fill the data grid view. Also I am using Visual Studio 2010 for programming
Thanks for your help in advance
Public Sub fillgrid()
Dim conn1 As String
conn1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filenamepath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
Dim connection As OleDbConnection = New OleDbConnection(conn1)
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection)
Dim ds As DataSet = New DataSet()
Dim emptyfile As String = "The file does not have any records for inserting."
Dim selectCmd As OleDbCommand = New OleDbCommand()
selectCmd.Connection = connection
selectCmd.CommandText = "SELECT * FROM [Sheet1$]"
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
da.SelectCommand = selectCmd
Dim dsCounter As Integer = da.Fill(ds, "[Sheet1$]")
If dsCounter = 0 Then
MessageBox.Show(emptyfile, "dsCounter")
End If
grvExcelData.DataSource = ds
grvExcelData.DataMember = "Sheet1"
grvExcelData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
da.Dispose()
If connection.State = ConnectionState.Open Then
connection.Close()
connection.Dispose()
End If
End Sub
Change
grvExcelData.DataMember = "Sheet1"
to
grvExcelData.DataMember = "[Sheet1$]"

failed to read the excel to sql database

I want to upload an Excel file and write data to sql server 2008.
The Excel file has 7 sheets and it writes in 7 tables.
Example : (sheetn -> temp_sheetn)
The code is working well but the last sheet is not writing in the last table.
The code is like this:
Partial Class app_UploadData
Inherits System.Web.UI.Page
Dim apps As New MyApps
Dim GlobReg As Integer = 0
Dim GlobOTC As Integer = 0
Private dt As DataTable = Nothing
Public Function xlsInsert(ByVal pth As String) As System.Data.DataTable
Dim strcon As String = String.Empty
If Path.GetExtension(pth).ToLower().Equals(".xls") OrElse Path.GetExtension(pth).ToLower().Equals(".xlsx") Then
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & pth & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Else
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & pth & ";Extended Properties=""Excel 12.0;HDR=YES;"""
End If
Dim strselect As String = "Select * from [Sheet1$]"
Dim exDT As New DataTable()
Using excelCon As New OleDbConnection(strcon)
Try
excelCon.Open()
Using exDA As New OleDbDataAdapter(strselect, excelCon)
exDA.Fill(exDT)
End Using
Catch oledb As OleDbException
Throw New Exception(oledb.Message.ToString())
Finally
excelCon.Close()
End Try
For i As Integer = 0 To exDT.Rows.Count - 1
' Check if first column is empty
' If empty then delete such record
If exDT.Rows(i)("CardNo").ToString() = String.Empty Then
exDT.Rows(i).Delete()
End If
Next
exDT.AcceptChanges()
' refresh rows changes
If exDT.Rows.Count = 0 Then
Throw New Exception("File uploaded has no record found.")
End If
Return exDT
End Using
End Function
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim ds As New DataSet()
Dim XlsConnString As String = String.Empty
Dim DirPath As String = Server.MapPath("~/Temp_Upload/")
Dim fName As String
If (Directory.Exists(DirPath)) Then
For Each fName In Directory.GetFiles(DirPath)
If File.Exists(fName) Then
File.Delete(fName)
End If
Next
End If
If xlsUpload.HasFile Then
Dim fileName As String = Path.GetFileName(xlsUpload.PostedFile.FileName)
Dim fileExtension As String = Path.GetExtension(xlsUpload.PostedFile.FileName)
Dim fileLocation As String = Server.MapPath("~/Temp_Upload/" & fileName)
xlsUpload.SaveAs(fileLocation)
'Check whether file extension is xls or xslx
If fileExtension = ".xls" Then
XlsConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension = ".xlsx" Then
XlsConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension <> ".xls" Or fileExtension <> ".xlsx" Then
lblMessage.Text = "Upload file must be excel !"
Exit Sub
End If
Dim cmd As New SqlCommand : Dim SheetName As String 'Dim dr As SqlDataReader
'Dim tran As SqlTransaction
apps.OpenConnection()
cmd.Connection = apps.oConn
Dim cn As New OleDbConnection(XlsConnString)
Try
cn.Open()
Catch ex As OleDbException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
' It Represents Excel data table Schema.
Dim dt As New System.Data.DataTable()
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt IsNot Nothing OrElse dt.Rows.Count > 0 Then
For sheet_count As Integer = 1 To dt.Rows.Count - 1
Try
' Create Query to get Data from sheet.
SheetName = dt.Rows(sheet_count)("table_name").ToString()
'Dim da As New OleDbDataAdapter("SELECT * FROM [" & sheetname & "]", cn)
'da.Fill(ds, sheetname)
'Execute a query to erase any previous data from our destination table
cmd.CommandText = "Truncate Table Temp_" & SheetName
cmd.ExecuteNonQuery()
'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(XlsConnString)
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [" & SheetName & "]"), OleDbConn)
'Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [Customer$]"), OleDbConn)
OleDbConn.Open()
Dim OleDbRead As OleDbDataReader = OleDbCmd.ExecuteReader()
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(apps.oConn)
bulkCopy.DestinationTableName = "Temp_" & SheetName
bulkCopy.WriteToServer(OleDbRead)
OleDbConn.Close()
OleDbConn = Nothing
Catch ex As DataException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
End If
cn.Close()
cn = Nothing
apps.CloseConnection()
End If
End Sub
End Class
The line that reads
For sheet_count As Integer = 1 To dt.Rows.Count - 1
should either be
For sheet_count As Integer = 0 To dt.Rows.Count - 1
or
For sheet_count As Integer = 1 To dt.Rows.Count
The first one I suspect, but I can't remember if this is a zero based list as I haven't got VB.Net installed here.
Incidentally there's no need to check the file extension is .xls and then to use the Jet provider, Microsoft.ACE.OLEDB.12.0 will work just fine on .xls files.