odbc reader for csv in vb.net - vb.net

I'm writing a program that should handle million of datasets in csv in a short time, my idea was to use odbc because of performance reasons, therefore i read all the data with odbc and save it in memory, thereafter i add parameters and insert it in sql db, here is my code so far:
Using connection As New OdbcConnection("jdbc:odbc:Driver={Microsoft Text Driver (*.txt; *.csv)};" & filePath & "Extensions=csv;Persist Security Info=False;")
Dim reader As OdbcDataReader
Dim i As Integer
Dim r As SeekZeilen
Dim TextFileTable As DataTable = Nothing
Dim line As String = reader.Read()
Me.ParseString(line)
Dim memStream As New MemoryStream(Encoding.Default.GetBytes(line))
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(memStream)
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
r.erste_Zeile = TextFileReader.ReadFields()
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
For i = 0 To r.erste_Zeile.Length - 1
Dim Column As New DataColumn(r.erste_Zeile(i))
Column.ReadOnly = True
TextFileTable.Columns.Add(Column)
Next
End If
DataGridView1.DataSource = TextFileTable
End Using
While reader.HasRows
line = reader.Read()
Me.ParseString(line)
memStream = New MemoryStream(Encoding.Default.GetBytes(line))
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(memStream)
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
DataGridView1.DataSource = TextFileTable
Try
r._Rest = TextFileReader.ReadFields()
ReplaceChars(r._Rest)
If Not r._Rest Is Nothing Then
Dim oSQL As New DBUmgebung.cdb.SQL()
oSQL.init()
AddParameters(oSQL, r)
oSQL.ausfuehrenSQL(DBUmgebung.cdb.KSQLCommand.INSERT, _table, "")
Dim dtRow As DataRow = TextFileTable.NewRow
For i = 0 To r._Rest.Length - 1
dtRow(i) = r._Rest(i).ToString()
Next
TextFileTable.Rows.Add(dtRow)
DataGridView1.Refresh()
Application.DoEvents()
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error! " & ex.Message & _
"")
Catch sqlEx As SqlException
MessageBox.Show(sqlEx.Message)
rtbSql.Focus()
Exit For
Catch ex As Exception
MessageBox.Show(ex.Message)
rtbSql.Focus()
Exit For
End Try
End Using
End While
reader.Close()
End Using
the problem is that i get null pointer exception for a unknown reason, does anyone have idea what i did wrong? is it probably because my odbc reader is not properly initialized?

Try this. This will read the csv file as all text into a datatable. Once in the Datatable you could then insert the records into SQL. You can always adjust this to handle multiple csv files.
Friend Shared Function GetExcelFile(ByVal strFileName As String, ByVal strPath As String) As DataTable
Try
Dim dt As New DataTable
Dim ConStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & ";Extended Properties=""Text;HDR=Yes;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & strFileName, conn)
da.Fill(dt)
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function

Related

Trying to convert Excel file into a Datatable and afterwards into a List of objects

I'm trying to convert a Excel-File into a DataTable and then into a List of Objects. My problem is, that the datatable is always empty, here is what i have tried:
First build the connection String
Public Function BuildConnectionString(excelPath As String) As String
If excelPath.Substring(excelPath.LastIndexOf(".")).ToLower = ".xlsx" Then
Return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & excelPath & ";Excel 12.0;HDR=YES;IMEX=1"
Else
Return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & excelPath & ";Excel 8.0;HDR=YES;IMEX=1"
End If
End Function
Convert Excel to Datatable (doesn't Work)
Private Function ConvertCSVToDataTable(ByVal path As String) As DataTable
Dim dt As DataTable = New DataTable()
Using con As OleDb.OleDbConnection = New OleDb.OleDbConnection()
Try
con.ConnectionString = String.Format(BuildConnectionString(path))
Using cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM [Sheet1$]", con)
Using da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(cmd)
con.Open()
da.Fill(dt)
con.Close()
End Using
End Using
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
If con IsNot Nothing AndAlso con.State = ConnectionState.Open Then
con.Close()
End If
End Try
End Using
Return dt
End Function
Convert DataTable to List of Objects
Private Function ConvertDataTableToCSVListOfISAACService(dt As DataTable, lst As List(Of ISAACServiceExcel)) As List(Of ISAACServiceExcel)
For Each row As DataRow In dt.Rows
Dim AnzahlParse As Double
Double.TryParse(row(Anzahl), AnzahlParse)
Dim EinzelkostenParse As Double
Double.TryParse(row(Einzelkosten), EinzelkostenParse)
Dim TotalParse As Double
Double.TryParse(row(Total), TotalParse)
Dim ISAAC As New ISAACServiceExcel(row(Leistungscode).ToString, row(KostenArt).ToString, row(UANR).ToString, row(Ueberbegriff).ToString, row(Benennung).ToString, AnzahlParse, row(Einheit).ToString, EinzelkostenParse, row(Summencode).ToString, row(AufPos).ToString, row(Komponente).ToString, row(Projektbeteiligter).ToString, row(Chefblattposition).ToString, TotalParse)
lst.Add(ISAAC)
Next
Return lst
End Function
You can also write code in C#, if thats easier for you. Thank you in advance!
I have a function that does this and is working fine.
Public Function loadExcelData(filename As String) As DataTable
Dim dt As DataTable = New DataTable
Using cn As New OleDbConnection
cn.ConnectionString = connString(filename)
Using cmd As New OleDbCommand
cmd.Connection = cn
cmd.CommandText = "SELECT * FROM [Plan1$]"
cn.Open()
Try
dt.Load(cmd.ExecuteReader)
Catch ex As Exception
MsgBox(ex.Message & vbCrLf & vbCrLf & ex.StackTrace, MsgBoxStyle.Critical)
Return Nothing
End Try
End Using
End Using
Return dt
End Function
But, in my case, I'm importing XLSX and XLS files, for CSV you can probably use something for a plain text, as you can find in this answer.

Trouble in displaying an image to datagridview

I'm having a trouble in viewing or displaying an image from the database (mysql) to datagriview
The table in my database that I'm trying to retrieve is named as sample with fields ID = Int(10), primary, auto increment and IMG = blob
Anyone who can help me with this? It will be so much appreciated
Sub getData()
Try
Dim Sql = "Select ID, IMG from sample"
connectionOn()
Dim cmd = New MySqlCommand(Sql, ConOn)
Dim dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGridView1.Rows.Clear()
While dr.Read = True
Dim mybytearray As Byte() = dr.Item("IMG")
Dim myimage As Image
Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream(mybytearray)
myimage = System.Drawing.Image.FromStream(ms)
DataGridView1.Rows.Add(dr(0), myimage)
End While
ConOn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Below is my code saving the image in the database. But it doesn't save anything. I want to get the image from the datagrid then save it to the database
Try
connectionSync()
Dim a, b As String
Dim Sql = "INSERT INTO SAMPLE (ID, IMG)values(#a,#b)"
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
a = Me.DataGridView1.Rows(i).Cells(0).Value.ToString()
Dim cmd As New MySqlCommand(Sql, ConSync)
Dim memorystream1 As New MemoryStream()
Dim filename As String = DataGridView1.Rows(i).Cells(1).Value
Dim bitmaps As New Bitmap(filename)
bitmaps.Save(memorystream1, Imaging.ImageFormat.Jpeg)
Dim pic() As Byte = memorystream1.GetBuffer()
cmd.Parameters.AddWithValue("#a", a)
cmd.Parameters.AddWithValue("#b", bitmaps)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
Next
ConSync.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Since MySql BLOB Type is used to stored SqlServer IMAGE Type I think you can adapt this code using MySql classes (i.e.: MySqlDataAdapter instead of SqlDataAdapter):
Try
Me.DataGridView1.DataSource = Nothing
Dim dgvID As New DataGridViewTextBoxColumn
dgvID.DataPropertyName = "ID"
Dim dgvIMG As New DataGridViewImageColumn
dgvIMG.DataPropertyName = "IMG"
Me.DataGridView1.Columns.Add(dgvID)
Me.DataGridView1.Columns.Add(dgvIMG)
connectionOn()
Dim cmdSample As SqlCommand = ConOn.CreateCommand
cmdSample.CommandText = "SELECT ID, " _
& "IMG " _
& "FROM Sample"
Dim dtSample As New DataTable
Dim daSample As New SqlDataAdapter(cmdSample)
daSample.Fill(dtSample)
Me.DataGridView1.DataSource = dtSample
ConOn.Close()
ConOn.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try

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.

How do I Iterate Through DataTable and Decrypt a field?

Good-day,
I need help with iterating through a DataTable (dbTable) and decrypting a particular field (ccNumber) before assigning its items to a Listview control (ListViewRecords).
I've already used the decryption code below elsewhere in my project on a Textbox with success, but can't figure out how to do it with the DataTable. Your assistance would be greatly appreciated, thanks.
HERE'S THE DECRYPTION CODE:
Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
Dim Hash As New System.Security.Cryptography.MD5CryptoServiceProvider
Try
DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(My.Settings.Key))
DES.Mode = System.Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(TextBoxCard.Text)
TextBoxCard.Text = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
MessageBox.Show("The following error(s) have occurred: " & ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
HERE'S THE CODE TO QUERY THE DB AND FILL THE LISTVIEW:
Private Sub loadRecords()
'FOR MySQL DATABASE USE
Dim dbConn As New MySqlConnection
Dim dbTable As New DataTable
Dim dbQuery As String = ""
Dim dbCmd As New MySqlCommand
Dim dbAdapter As New MySqlDataAdapter
dbTable.Clear()
Try
If dbConn.State = ConnectionState.Closed Then
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
dbConn.Open()
End If
dbQuery = "SELECT *" & _
"FROM cc_master INNER JOIN customer ON customer.accountNumber = cc_master.customer_accountNumber " & _
"ORDER BY nameCOMPANY ASC"
With dbCmd
.CommandText = dbQuery
.Connection = dbConn
End With
With dbAdapter
.SelectCommand = dbCmd
.Fill(dbTable)
End With
ListViewRecords.Items.Clear()
For i = 0 To dbTable.Rows.Count - 1
With ListViewRecords
.Items.Add(dbTable.Rows(i)("ccID"))
With .Items(.Items.Count - 1).SubItems
.Add(dbTable.Rows(i)("nameCOMPANY"))
.Add(dbTable.Rows(i)("ccNumber"))
.Add(dbTable.Rows(i)("ccExpireMonth"))
.Add(dbTable.Rows(i)("ccExpireYear"))
.Add(dbTable.Rows(i)("ccType"))
.Add(dbTable.Rows(i)("ccAuthorizedUseStart"))
.Add(dbTable.Rows(i)("ccAuthorizedUseEnd"))
.Add(dbTable.Rows(i)("ccLocation"))
.Add(dbTable.Rows(i)("cardholderSalutation"))
.Add(dbTable.Rows(i)("cardholderLastname"))
.Add(dbTable.Rows(i)("cardholderFirstname"))
.Add(dbTable.Rows(i)("ccZipcode"))
End With
End With
Next
Catch ex As MySqlException
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
dbConn.Close()
End Sub
Put the decryption thing in a function:
Function Decrypt(ByVal ToDecrypt) as String
Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
Dim Hash As New System.Security.Cryptography.MD5CryptoServiceProvider
Try
DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(My.Settings.Key))
DES.Mode = System.Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(ToDecrypt)
return System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
return "Whatever failed message you want"
End Try
End Function
Then loop through your table like this and change the value:
for i as Integer = 0 to dbTable.Rows.Count - 1
dbTable.Rows(i)("ccNumber")) = Decrypt(dbTable.Rows(i)("ccNumber"))
This should work if I'm not totally off.

How to use ACE OLEDB to import Excel data into VB?

Originally I was using Office Interop to import data, but that was a headache and a half for both me and my computer. Right now I'm attempting to load it with ACE, but my data grid isn't being populated. Once that's up and running I need to know how to use that data in other ways, and how to grab specific cells of data from that DataSet. I'm using Visual Studio 2008, by the way.
Right now I have...
Public Function funcUpdate(ByVal sFileLoc As String) As Boolean
'Determine connection string properties
Dim dbProperty As String
If updFileExt = ".xlsx" Then
dbProperty = "Excel 12.0 Xml;HDR=No"
ElseIf updFileExt = ".xls" Then
dbProperty = "Excel 12.0;HDR=No"
Else
MessageBox.Show("FATAL: File type error on updater", "OHGAWDNO", MessageBoxButtons.OK, MessageBoxIcon.Error)
updateTerm()
Return False
End If
Dim dbConn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & updFile & ";Extended Properties=" & dbProperty & ";")
Dim dbCommand As New OleDb.OleDbDataAdapter("select * from [sheet1$]", dbConn)
Dim dtSet As New DataSet
Try
dbCommand.TableMappings.Add("Table", "ExcelTest")
dbCommand.Fill(dtSet)
Form1.DataGrid1.DataSource = dtSet.Tables(0)
Catch exlErr As Exception
Finally
dbConn.Close()
End Try
updateTerm()
End Function
Try to do this.
Dim path As String = "c:\example.xlsx"
Dim constr As String = [String].Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;" & _
"HDR=YES;IMEX=1;""", path)
Dim adapter As New OleDbDataAdapter
Using cn As New System.Data.OleDb.OleDbConnection(constr)
Try
cmdselcet = New OleDbCommand("SELECT * FROM [Sheet1$]", cn)
cn.Open()
adapter.SelectCommand = cmdselcet
Dim ds As DataSet
ds = New DataSet
'Display
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
MsgBox("Done!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using