How can I use the Database Toolbox to access a CSV file?

6 views (last 30 days)
I would like to use database functionality such as sorting, etc. when accessing a CSV file.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 2 Dec 2009
The first step is to create a file called "schema.ini" in the same folder that contains the CSV file. The schema file will contain information about the data format for all files in the containing folder.
The schema file is needed by the database driver in order to be able to interpret the CSV data correctly.
The following entry is an example for a file called "TestFile.csv", the first line of which contains the header names, uses commas as delimiters and contains two columns containing string data:
[TestFile.csv]
ColNameHeader=True
Format=Delimited(,)
MaxScanRows=0
CharacterSet=OEM
Col1=FIELD1 Char Width 255
Col2=FIELD2 Char Width 255
You can also use the ODBC Manager and create a DSN for your file. The Manager has a graphical interface to specify the above configuration data and will create the schema file automatically.
The following code demonstrates how to access the above file:
% Set return format.
setdbprefs('DataReturnFormat','cellarray');
% Open connection specifying the folder that contains the file to read.
conn = database('','','','sun.jdbc.odbc.JdbcOdbcDriver',['jdbc:odbc:Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=' pwd ';Extensions=asc,csv,tab,txt'])
% Read all fields from one file.
curs = exec(conn,'SELECT * FROM TestFile.csv');
curs = fetch(curs);
data = curs.data
% Clean up.
close(conn);

More Answers (0)

Products


Release

R2009b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!