Type Mismatch when combining two csv files in VB - sql

I had my code working just fine, but when I generated new updated versions of the CSV files it suddenly errors out on me and gives me a type mismatch catch.
Here is the code that I have right now.
Dim A As String = "ADusers.csv"
Dim B As String = "MlnExp.csv"
Dim filePath As String = "C:\CSV"
Try
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & (filePath) & "\;Extended Properties='text;HDR=Yes'"
Dim sSql As String = "SELECT *" _
& "FROM ([" & (B) & "] B LEFT JOIN [" & (A) & "] A ON B.EmployeeNumber = A.employeeID)"
Dim conn As OleDb.OleDbConnection = New OleDb.OleDbConnection(ConnectionString)
Dim Command As OleDb.OleDbCommand = New OleDb.OleDbCommand(sSql, conn)
Command.CommandType = CommandType.Text
conn.Open()
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sSql, conn)
Dim dt As DataTable = New DataTable
da.Fill(dt)
DataGrid1.DataSource = dt
DataGrid1.Update()
conn.Close()
lblStatus.Text = "CSV combined... Now saving to file."
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
End Try
Before it would go through, combine the two CSV files, and then display them in my datagrid. But now my catch is throwing back
Type mismatch in expression

i would check B.EmployeeNumber = A.employeeID
in both of your file one is a text value (left align) and the other is a a interger(right align)

Related

Load Report failed with crystal report

I got an error (load report failed) when trying to print crystal report in my vb.net application
but my problem is (this error hasn't occurred always) maybe after printing unknown number of reports, then once this error has occurred.
Here is my code:
Dim cmd As New OleDbCommand
Dim connp As New OleDbConnection
Dim da As New OleDbDataAdapter
Dim ds As New DataSet
Dim strsql As String
Dim strreprotname As String
Try
connp.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Application.StartupPath & "\report.mdb; Jet OLEDB:Database Password=KNOZ1003"
connp.Open()
ds.Reset()
strsql = "select * from tab3"
cmd.CommandText = strsql
cmd.Connection = connp
da.SelectCommand = cmd
da.Fill(ds)
strreprotname = "cashrpt"
Dim strreportpath As String = Application.StartupPath & "\Reports\" & strreprotname & ".rpt"
Dim rptdocument As New CrystalDecisions.CrystalReports.Engine.ReportDocument
Dim prnset As New Printing.PrinterSettings
Dim pg As New Printing.PageSettings
rptdocument.Load(strreportpath)
rptdocument.SetDataSource(ds.Tables(0))
rptdocument.SetDatabaseLogon("", "", "", Application.StartupPath + "\report.mdb")
prnset.PrinterName = cashprinter
rptdocument.PrintToPrinter(prnset, pg, False)
cmd.Dispose()
connp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Import Excel File to Data Set in VB

I'm trying to import an Excel file into a DataSet in VB. My code that I'm using for this looks like this:
Dim StrSql
Dim ExcelCon As New OleDbConnection
Dim ExcelAdp As OleDbDataAdapter
Dim ExcelComm As OleDbCommand
Dim Col1 As DataColumn
Try
ExcelCon.ConnectionString = "Provider=SQLNCLI11;" & _
"Data Source = " & strpath & _
";Extended Properties=""Excel 8.0;"""
ExcelCon.Open()
StrSql = "SELECT * From [$Sheet1$]"
ExcelComm = New OleDbCommand(StrSql, ExcelCon)
ExcelAdp = New OleDbDataAdapter(ExcelComm)
objDT = New DataTable()
ExcelAdp.Fill(objDT)
Col1 = New DataColumn
Col1.DefaultValue = 0
Col1.DataType = System.Type.GetType("System.Decimal")
Col1.Caption = "Sr No."
Col1.ColumnName = "SrNo"
objDT.Columns.Add(Col1)
Col1.SetOrdinal(1)
ExcelCon.Close()
Catch ex As Exception
Finally
ExcelCon = Nothing
ExcelAdp = Nothing
ExcelComm = Nothing
End Try`
The error I am receiving says "Invalid connection string attribute". Does anyone know how to fix this error? I am using Excel 2010, if that helps. Thanks in advance.

Syntax error (comma) in query expression, header with commas

I am trying to check if value from label1 exist in dbf file column named : "NALOG,C,8". Header in DBF file I can not change, 'cause it represents column's format and field size. But with that I get this error : "Syntax error (comma) in query expression "NALOG,C,8 = #NAL"
Here is complete code :
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"
'Dim SQLstr As String = "SELECT * FROM " & DBF_File
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV;User ID=Admin;Password="
'cmd = New OleDbCommand("SELECT * FROM " & DBF_File)
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE " & ColName & " = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", Label1.Text)
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST" & TextBox1.Text
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
end using
Thanks.
If you have a column that is named this:
Dim ColName As String = "NALOG,C,8"
Then I would change it too this:
Dim ColName As String = "[NALOG,C,8]"
Use this instead:
Dim ColName As String = "NALOG"

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

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.