FROM clause of INSERT INTO throwing unhandled exception in VB - vb.net

I'm running VB 2019, trying to import a CSV file into an Access database using this code:
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + My.Settings.DataLoc + "\PassMan.accdb;Jet OLEDB:Database Password=" + My.Settings.Authentication + ";")
Dim command As OleDb.OleDbCommand = New OleDb.OleDbCommand()
conn.Open()
Dim cmd As New OleDbCommand("INSERT INTO Passwords SELECT * FROM [text;FMT=Delimited;HDR=yes;DATABASE=" + My.Settings.DataLoc + "\PassMan.accdb] AS " + Path.GetFileName(ReadFile), conn)
cmd.ExecuteNonQuery()
ReadFile is defined by the user as a filename based on an OpenFileDialog. The name of the file I provide at runtime exists. The database file exists and is available, not open by any other app (I've used the same conn code elsewhere in the app).
I get an unhandled exception in the FROM clause in the INSERT INTO statement:
System.NullReferenceException: 'Object reference not set to an instance of an object.' System.Exception.InnerException.get returned Nothing.
What's the problem? How do I solve it? I'm stuck!

Related

Mapping onedrive files to string for OLEDB to read specific files within drive Visual Basic .NET

I have a program that reads an excel file that is on my local disk. I need this file to be accessible to other individuals to edit the file and allow the program to execute based on its contents. The way were making this accessible is sharing it via OneDrive. The file is read by a OLEDB Script I wrote that takes the directory of the file to read it and load into temp table on the app. I have been searching online for a solution to this in visual basic but a lot of the solutions are written in c# and its hard for me to translate or understand the logic. Here is an example of the solution in pseudo code:
If (ONEDRIVE_FILE_DIRECTORY IsNot Nothing) Then
' STORE FILE FROM ONE DRIVE INTO LOCAL_FILE_DIRECTORY
End If
Dim strConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="LOCAL_FILE_DIRECTORY";Extended Properties=""Excel 8.0;HDR=YES"";"
Dim dt As New DataTable
dt.TableName = "Results"
dt.Columns.AddRange(New DataColumn() {New DataColumn("LOC_ID", GetType(String)),
New DataColumn("EMAIL", GetType(String)),
New DataColumn("INTERVAL", GetType(String)),
New DataColumn("PASSWORD", GetType(String))
})
Dim connection As OleDbConnection = New OleDbConnection(strConnectionString)
Dim strSQL As String = "SELECT [LOC_ID], [EMAIL], [INTERVAL], [PASSWORD] FROM [Report$] WHERE [LOC_ID] <> ''"
Try
connection.Open()
Using Adp As New OleDbDataAdapter(strSQL, connection)
Adp.Fill(dt)
End Using
Catch ex As Exception
LogMessage(ex.ToString, "Error message in """ & strApplicationName & """ job on " & strComputerName & " by: " & strUsername)
SendEmailErrorMessage(ex.ToString)
Finally
If connection.State = ConnectionState.Open Then
connection.Close()
End If
End Try

VB.NET. How to get data from sdf database?

We are developing windows form app. We have local database which is sdf file. We added reference to our project: SQLServerCe.dll
We are using this code:
Dim strDataSource As String
strDataSource = "Data Source = C:\Users\JOE\Desktop\Class work (7)\Class work\BookIt\BookIt.DBEntity\Library.sdf"
Dim conn As New SqlCeConnection
conn.ConnectionString = strDataSource & ";Password='<password>'"
Dim selectCmd As SqlCeCommand = conn.CreateCommand
selectCmd.CommandText = "SELECT author, title FROM book"
Dim adp As New SqlCeDataAdapter(selectCmd)
Dim ds As New DataSet
' Note: Fill will leave the connection in its original state;
' In this case, the connection was closed so it will be left closed
adp.Fill(ds)
tbAuthor.Text = ds.Tables(0).Rows(0)(0).ToString()
tbTitle.Text = ds.Tables(0).Rows(0)(1).ToString()
This code is not working. This line is giving error:
adp.Fill(ds)
Error: An unhandled exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll
What we are doing wrong? How to solve this problem?
Open the database connection before you create your command object, ie conn.Open()

External table is not in the expected format error while trying to access Excel

I am trying to access Excel from my vb application by using the Oledb Connection .
Here is my connection string:
<add key="ExcelConnection" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties="Excel 12.0 Xml;HDR=NO;IMEX=1;MAXSCANROWS=1000;READONLY=FALSE;"" />
Here is the code:
Dim connection As New System.Data.OleDb.OleDbConnection(ExcelConnectionString)
connection .Open()
Dim schTbl As DataTable = connection .GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, Nothing)
Dim dbAdapter As System.Data.OleDb.OleDbDataAdapter
Dim execQuery As String
Dim rtnData As System.Data.DataTable
execQuery = "SELECT * FROM [" & schTbl.Rows.Item(0)("TABLE_NAME") & "]"
dbAdapter = New System.Data.OleDb.OleDbDataAdapter(execQuery , ExcelConnectionString)
dbAdapter.Fill(rtnDat )
dbAdapter.Dispose()
connection .Close()
schTbl .Reset()
What my problem is that ,the above is working 70% of the times but rest of the times i am getting the following error:
System.Data.OleDb.OleDbException (0x80004005): External table is not in the expected format.
Could anyone please help me that why at times i am getting this error .Is there any way to rectify it or any other way to achive the same result.
Any help will be appreciated.
Thanks
External table is not in the expected format. typically occurs when trying to use an Excel 2007 file.
Using the following connection string seems to fix most problems.
dim path as string = yourfilepath
dim connStr as string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;"
Edit
some times this too may fail in a case when your are using an .xlsx file.if that is the case you should install a JET database engine in your pc to override those errors.it is availale http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en

Executing an SQL query in an Access Database in VB.NET

I have already posted one question about this piece of code before lol. But now I am having a different problem and need help with it. Basically this is code for a search button on a Windows Form coded in VB.NET.
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim cnnOLEDB As New OleDbConnection
Dim cmdOLEDB As New OleDbCommand
Dim strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & System.Environment.CurrentDirectory & "\All Keyed Up, Lock & Safe, LLC.accdb"
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
Dim Connection As New SqlClient.SqlConnectionStringBuilder
Connection.DataSource = "file:///C:\Users\thelukester145\Documents\All%20Keyed%20Up\All%20Keyed%20Up,%20Lock%20&%20Safe,%20LLC.accdb"
Dim objSQLConnection = New SqlClient.SqlConnection(Connection.ConnectionString)
Dim cmd As New SqlCommand()
Dim myTable As New DataTable()
Dim SearchFor = SearchBox.Text
If AddressButton.Checked Then
cmd.Connection = objSQLConnection
cmd.CommandText = "SELECT * FROM [McDonald's-Corporate Stores] WHERE [Address] LIKE '%" & SearchFor & "%'"
Dim myAdapter As New SqlDataAdapter(cmd)
myAdapter.Fill(myTable)
DataGrid.DataGridView1.DataSource = myTable
ElseIf NumberButton.Checked Then
cmd.Connection = objSQLConnection
cmd.CommandText = "SELECT * FROM [McDonald's-Corporate Stores] WHERE [McOpCo#] LIKE '%" & SearchFor & "%'"
Dim myAdapter As New SqlDataAdapter(cmd)
myAdapter.Fill(myTable)
DataGrid.DataGridView1.DataSource = myTable
End If
DataGrid.Show()
cnnOLEDB.Close()
End Sub
The database that is attempting to be searched is a database of customers for our family buisness. I am trying to search by either the address or store number of our customer. I've worked through who knows how many fatal errors but the newest one has me sort of stumped. It is crashing on myAdapter.Fill(myTable). The error message it gives is this:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)
Any help would be much appreciated :)
Well, you are freely mixin OleDb classes with SqlClient classes. The two are for different database types. OleDb is needed for Access, SqlClient classes are used for Sql Server.
So you need to change all the classes SqlCommand, SqlCommandBuilder, SqlDataAdapter,SqlConnectionStringBuilder with the corresponding classes OleDbCommand, OleDbCommandBuilder, OleDbDataAdapter, OleDbConnectionStringBuilder
Infact, the error message is emitted by the SqlClient library that tries to use your connection string as it was a connectionstring for an SQL Server database and, of course, it fails to find it.
Also, I am not sure about that, but probably the DataSource property doesn't need the prefix file:/// and the Encoding of spaces with %20

select data from Dataset Vb.Net

ok first ill explain what ive done.
First I imported an access db into my vb app it then named the dataset etc.
this is how my dataSet looks:
1 table
4 columns
so Far i have this:
Dim ds As ElementsDataSet
Dim dt As ElementsDataSet.ElementsDataTable
Dim conn As SqlConnection = New SqlConnection("Data Source=|DataDirectory|\Elements.accdb")
Dim selectString As String = "Select Atomic Mass FROM Elements WHERE No =" & mol
Dim cmd As New SqlCommand(selectString, conn)
If conn.State = ConnectionState.Closed Then conn.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
While datareader.Read = True
MessageBox.Show(datareader.Item("Atomic Mass"))
End While
datareader.Close()
and upon executing this I get this error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
The problem is you are using a SQLConnection to open a Access database. This wont work.
You either need a SQLServer database or to use the OleDbConnection for a Access database.
Here is a Microsoft KB article to help you connect to the Access database:
How To Retrieve and Display Records from an Access Database by Using ASP.NET, ADO.NET, and Visual Basic .NET and this one over at CodeProject: http://www.codeproject.com/Articles/8477/Using-ADO-NET-for-beginners
Private Sub ReadRecords()
Dim conn As OleDbConnection = Nothing
Dim reader As OleDbDataReader = Nothing
Try
conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\Elements.accdb"))
conn.Open()
Dim cmd As New OleDbCommand("Select Atomic Mass FROM Elements WHERE No =" & mol, conn)
reader = cmd.ExecuteReader()
While reader.Read = True
MessageBox.Show(reader.Item("Atomic Mass"))
End While
Finally
If reader <> Nothing Then
reader.Close()
End If
If conn <> Nothing Then
conn.Close()
End If
End Try
End Sub