OledDbDataAdapter "Syntax error in FROM clause" exception - c#

I'm using OleDB to import data into grid from text file with extension ".K$$".
Here's some example code:
FileInfo file = new FileInfo(filename);
string connectionString = "";
OleDbDataAdapter adapter;
OleDbConnection con;
connectionString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + file.DirectoryName + ";Extended Properties=\"Text;Format=TabDelimited;\"";
con = new OleDbConnection(connectionString);
con.Open();
adapter = new OleDbDataAdapter(String.Format("SELECT * FROM {0} ", file.Name), con);
adapter.Fill(MyDataTable);
when executing the Fill method it throws the exception. What's wrong with the FROM clause? Thanks
EDIT:
Ok, after some tests I found out that the problem is with the "$" symbols. Maybe it's some reserved symbol ?
Also, if I rename the extension to ".txt" the file got loaded into the grid but it only have 1 column , which means it can't see that there're tabs in the rows.
Another issue is that when I change the file extension to something different than ".txt" (for ex. ".tx") the Fill method throws exception "Cannot update. Database or object is read-only".

OK, I just tried creating an example.K$$, and then tried to connect to it using the same provider as stated through Server Explorer in Visual Studio 2010. Its an Unrecognised format.
I don't think this will ever work.
You may need to look at connecting via a different provider or method.
I think You should look at this link :-
EDIT :
http://www.codeproject.com/Articles/6737/Fill-a-DataSet-from-delimited-text-files
It will allow you to read your txt file into a datable correctly.

Try checking the path of the filename if its correct

Check that neither the directory, nor the filename, contain spaces. If they do, you'll need to escape/quote them.
You'll also need to quote the filename if it contains an extension since the . is not a valid character in the FROM clause. Try FROM [{0}] (though this may not be the correct quoting character for the OleDbDataAdapter).

Related

OleDbConnection error 'External component has thrown an exception' when connecting to Excel file

My WinForms application reads data from an Excel file to a DataTable. On the first call, everything works as it should. On the second call (15 minutes later, regulated by a System.Timers.Timer), I get the following error at the line conn1.Open();:
External component has thrown an exception
I have searched StackOverflow but have not found anything that quite answers this issue. I have read OleDbConnection gets "External component has thrown an exception.", however that suggests checking the build configuration platform in Visual Studio, which in my case must be correct as the code executes correctly on first calling.
Below is my code:
DataTable dt = new DataTable();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Mode=Read;Extended Properties=\"Excel 12.0 XML;HDR=Yes\"";
FileInfo file = new FileInfo(path);
OleDbConnection conn1 = new OleDbConnection(connectionString);
conn1.Open(); //Exception is thrown here on second calling
OleDbDataAdapter da = new OleDbDataAdapter(string.Format("SELECT * FROM [Sheet1$]"), conn1);
da.Fill(dt);
The path is always a new file. The old file is replaced by a new file (with a different file name) on every calling.
I have been struggling with this for a few days now, any help is appreciated.
Just stripped the code down, line by line, and it turns out that removing the following line makes the code work:
FileInfo file = new FileInfo(path);
If anyone has any suggestions as to why this is the case, I would be interested to know.

Mixed Data Type in Excel, IMEX Doesn't Work

I am trying to export xls into datatable. Below is my connection string.
string path = //xls source path
OleDbConnection MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + path + "';Extended Properties='Excel8.0;IMEX=1;TypeGuessRows=0;HDR=No;ImportMixedTypes=Text'");
I set IMEX=1 and all the other extended properties as I have to deal with mixed datatypes.
Even though I set the connection like that yet I still produced error.
There are no error messages, but the inconsistent rows (who don't follow the majority datatype are set to null instead).
Can someone tell me what did I miss? Btw, I am using the OleDbDataAdapter & Fill(DataSet) method.
Are you sure that TypeGuessRows=0; and ImportMixedTypes=Text; are working from connection string and should not be modified in registry (HKEY_LOCAL_MACHINE\SOFTWARE\[Wow6432Node\]Microsoft\Jet\4.0\Engines\Excel)? AFAIK this settings are read from registry. ImportMixedTypes=Text is usually by default, but TypeGuessRows=8, and should be set to 0 as in your connection string.

Reading A Fixed Format Text File

Its been years since I have had to attempt to read a file using either Microsoft Text ODBC Driver or Microsoft Jet OLE DB 4.0 Provider.
So I have the following code
public void Example()
{
string CVS = Application.StartupPath;
string SQL = "SELECT * FROM [MyFile.txt]";
string Connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+CVS+";"+"Extended Properties='text;HDR=Yes;FMT=Fixed;";
OleDbDataAdapter OLE = new OleDbDataAdapter(SQL,Connection);
DataTable Table = new DataTable();
OLE.Fill(Table);
}
When I run the above code I get an "Unexpected Error", I know I am missing something, I am not sure what exactly.
Sources:
http://www.connectionstrings.com/textfile
http://www.connectionstrings.com/Providers/net-framework-data-provider-for-ole-db
http://www.aspdotnetcodes.com/Importing_CSV_Database_Schema.ini.aspx
Any direction would be appreciated.
Let us assume the Schema.ini file is correct.
Remove ' (just prior to 'text;) from the connection string.
In order to resolve the "Could not find installable ISAM", run the following command:
Regsvr32 c:\winnt\system32\mstext40.dll
* Make sure that file is in that folder first. And change WINNT to whatever your windows directory is.
I know this is not a real answer to your question, but i would really rethink about using this architecture to read in a file.
I would really prefer something like CSV Reader, cause it gives you much more power about how the data will be interpreted. Alternative you could also take a look into the FileHelpers.

c#, oledb connection string issue

I'm using .net4.0 and c# language.
In my code i have a connection string
oleConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;
Data Source = " + filepath + ";
Extended Propertie s= \"Excel 12.0;HDR=yes\"";
and it work well. But when i change a connection string like this:
oleConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;
Data Source =" + filepath + ";
Extended Properties =\"Excel 12.0;HDR=no\"";
(I change HDR parameter for "no")
I got error: No value given for one or more required parameters.
error from "Microsoft Office Access Database Engine".
If your referencing a column using say [A1] then this will fail. With HDR=No the columns are referenced as F1, F2 etc.
OleDb Connection HDR Default is YES ans there is no option for that.
Check:
Connection strings for Access 2007
Regards
There is no HDR=no....
The default behavioour is no headers. So just leave out the HDR part completely - that will also mean no headers.
More info:
http://msdn.microsoft.com/en-us/library/ms254500.aspx

Can a .csv file be used as a data source in Visual Studio 2008?

I'm pretty new to C# and Visual Studio. I'm writing a small program that will read a .csv file and then write the records read to a SQL Server database table.
I can manually parse the .csv file, but I was wondering if it is possible to somehow "describe" the .csv file to Visual Studio so that I can use it as a data source? I should mention that the first two lines in the .csv file contain header information and the following lines are the actual comma-delimited data.
Also, I should mention that this program is a stand-alone console program with no user interface.
This is a great example of using the power of LINQ. Here's a quick reference with an example of how to do it.
The run down is this. You can read in your CSV to a string array, then use LINQ to query against that collection. As Reed points out though, you'll have to code around your header line, as it will throw off your query.
You can also use the TextFieldParser too to handle escaping commas. Here's an example on thinqlinq that uses the TextFieldParser to parse the file, and a LINQ query to get the results. It even has a unit test to make sure escaped commas are handled.
If you have a 2 line header, it's not a standard CSV file.
In this case, the automatic tools won't work, and you'll have to revert to parsing the file manually.
If you want to remove one of the header lines, you might be able to use this technique of parsing CSV files into an ADO.NET DataTable.
If not, however, the TextFieldParser in the Microsoft.VisualBasic.dll assembly (usable from C# too) makes parsing CSV files very simple.
To parse it manually is very simple, and you could have a program that parses it, strips out the first two unnecessary lines and then feeds it directly to SSIS.
Here is a link for using LINQ to read it in:
http://blogs.msdn.com/wriju/archive/2009/05/24/linq-to-csv-getting-data-the-way-you-want.aspx
Using The Built In OLEDB CSV Parser via C# in order to parse a CVS file.
You can find a sample here
It basically lets you treat the csv file like a database table.
The link in Development 4.0's post has dissapeared. The code in that link was the following:
class CSVParser
{
public static DataTable ParseCSV(string path)
{
if (!File.Exists(path))
return null;
string full = Path.GetFullPath(path);
string file = Path.GetFileName(full);
string dir = Path.GetDirectoryName(full);
//create the "database" connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"text;HDR=No;FMT=Delimited\"";
//create the database query
string query = "SELECT * FROM " + file;
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
try
{
//fill the DataTable
dAdapter.Fill(dTable);
}
catch (InvalidOperationException /*e*/)
{ }
dAdapter.Dispose();
return dTable;
}
}
}

Categories