Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

ColdFusion Techniques: Test & Excel ODBC

ColdFusion Techniques: Test & Excel ODBC

Recently I needed to create an ODBC source that would allow an application to read and write from a text file. An obvious question is: Why would I use ODBC to read from and write to a text file? After all, ColdFusion supports this easily using the <CFFILE> tag. You'd be right if you were talking about a purchased copy of ColdFusion. My requirements involved ColdFusion Express, which doesn't support the <CFFILE> tag.

Unfortunately, there's little, dare I say no, documentation on how to use ODBC against text files. There was no information in the CF manuals, nothing on Allaires Web site, and nothing in the ODBC documentation from Microsoft.

On the surface it seemed simple. But it wasn't. There were some surprises along the way. Eventually the mystery was solved, and I was able to read from and write to a text file. In the process I also decided to explore reading from and writing to an Excel spreadsheet directly using the Microsoft ODBC driver.

The Situation Defined
As I explained, the application required the use of ColdFusion Express. This is the free version from Allaire that can be downloaded from their Web site. It has many of the capabilities of the full version. However, there are limits, and one was the lack of support for directly reading from and writing to text files. And, as the <CFFILE> tag wasn't available, I needed a method to access information in a text file and output information into another text file.

This prompted the search for documentation. It's probably somewhere on the Web, but I couldnt find it easily. Even a question posted in the developer conference failed to produce a timely answer to my needs. So I set off on my own.

Defining the Source
The first thing to do was define an ODBC source for the text files. I created a directory and placed a text file in it. The contents of the file are shown in Figure 1. Then I brought up the CF Administrator and created an ODBC source selecting the text file. The connection wouldnt verify. Okay, so step back, think, and perhaps look more closely at the screen in the CF Administrator.

The CF Administrator screen clearly says "database directory." And there's a box on the CF Administrator screen that says "Extensions List" and has the values "asc,csv,tab,txt" listed in the box. I changed the data source to point to the directory, then put "txt" in the Extensions List box. The connection now verified correctly. This indicates that the ODBC connection must point to a DIRECTORY that contains the text file or files. The "Extensions List" needs to contain the extension of the file or files desired. Adding additional extensions separated by commas can process multiple types of files.

Accessing the Data
Now it was time to try to access the data in the text file that was placed in the directory. I was clueless about how the SQL would be constructed to access the data, so some trial and error was needed.

I guessed correctly that the table name would be the name of the text file by virtue of the ODBC setup in the CF Administrator pointing to a directory instead of a file. Id placed two records in the table with the data comma-delimited as that seems to be a common method of separating text data. I wrote a small script to access the file, which did nothing but select data from the file using only the file name as the table name. It returned an ODBC error and failed to work. I then added the extension of the file to the table name, making the SQL Select * from address.txt. That was successful, so it was obvious that the fully qualified file name is required even though "txt" was specified in the ODBC setup.

The next thing was to see the names of the columns that were returned from the query. I knew that the variable query-name.ColumnList, where queryname is the name of the query, contains a list of column names returned from the query. Since Id selected all columns, this variable would show me all the columns that were returned.

I was pleasantly surprised to find that the column names consisted of the comma-delimited values in the first record. A little experimentation showed that column names could have spaces in them as long as they had brackets around them in the query. For example, a column name of First Name would be [First Name] in the SQL for the query.

I then extended the script to output the data that was in the text file. It appeared as expected, with data from the text file starting at the second row as data. A comma was needed between each data field in the text file. I also discovered that if your data contains commas, then simply surround each field with double quotation marks. If your data contains double quote marks, then escape the double quote marks by placing two double quote marks in a row. The problem of reading in data from a text file was solved. The first row is the column name, commas separate the data, and the table name is the fully qualified name of the file with the extension. It was even possible to select only specific rows by using a WHERE clause in the query.

Outputting the Data
Now it was time to create data in a text file using the ODBC driver. Since I already knew that the column names would be placed in the first row of the table, I felt it should be easy to create a file.

The first thing was to create a file with the proper headings, which I could have done by creating the file with just the column names using any standard text editor. But the idea was to make the entire process automatic. I looked for clues in "Help" for MS Access and found some information on creating a table. The code for creating a table is shown in Listing 1. For this example I created a file with text, numeric, and date fields. I don't know if this really matters for a text file, but it certainly helps to document what you're trying to create.

Next, I wrote a small script to place data in the text file. The query was the same as would be used for any "classic" database. After running the script I looked at the file with a text editor, and the data was in the file almost as expected. The text data was always surrounded by double quotes even though they were not specified when the data was written. For the numeric fields I was never able to figure out how to specify the number of decimal places. You can use NUMBER for a field type and get a field with two decimal places. The result of the code is shown in Listing 2.

At this point I had all the information I needed to create a text file using an ODBC driver. The last piece of information was how to eliminate the file if it existed. Any attempt to run the SQL code that created the file would cause an exception if the file (or table) already existed. Since CF Express doesn't support the CFFILE tag, another method had to be devised to delete a file. Id already used ODBC to create a table, so why not use ODBC to delete one? It was certainly worth a try.

I used the CF tag <CFIF FileExists()> to look for the presence of the file (or table) and, if it existed, then use some SQL to delete it. The result was the code in Listing 3. If the file (or table) existed, it would be deleted using the DROP SQL command; it could then be re-created. Note: When using the FileExists() function, it's necessary to fully qualify the file (or table) name with the drive and directory.

Notable Limitations
One thing you cant do with ODBC is update the data in the file. You cant use the UPDATE SQL or DELETE SQL commands; all you can do is INSERT data. And any inserts are placed at the end of the existing data. So you can add to a text file, but that's about it. If you really needed to update the data, youd have to use two tables - reading from one table, then inserting into another. This would be tedious.

I also observed that the process of writing the file was extremely slow: it took almost 45 seconds to write 100 records to the file. This was done on a Pentium 450 with ColdFusion and the ODBC source on the same system. (This was a top-notch system two year's ago; now it's low end.) This Isn't something youd want to use for large volumes of data. Reading the data was reasonably quick, but writing was painfully slow.

This did accomplish the goal of allowing the reading and writing of text files with ColdFusion Express.

Excel Data Source
With the problems of text files out of the way it was time to turn my attention to discovering how to use an MS Excel file as a data source. Fortunately, I had some documentation on how to use MS Excel as an ODBC data source, so this should have been easy. Unfortunately, the documentation was incorrect - the examples it gave wouldnt work.

Now, this may be due to the version of Excel Im using. The Administrator clearly only allows files created with Excel version 3.0, 4.0, or 5.0. The only version I had was Excel 2000, and I was using the "Save As" option to save the file as Excel 5.0. Regardless, I couldnt get CF to work according to the example.

Setting up the data source was no problem, and unlike a text source that points to a directory, the data source for Excel points to a file. This implies that the data to be used as tables is contained within the Excel file.

The example I had says that you must have a data sheet with a name that contains a dollar sign ($) as the last character. You then use this name as the table name in the query and place it in quotes. Well , it just flat out wouldnt work. I tried removing the trailing dollar sign from the sheet name. I tried using single quotes and double quotes. I removed the trailing dollar in the query. Every combination I tried failed for syntax error in the query or not being able to find the table.

I then highlighted the data in the sheet and gave it a name by using the menu items "Insert, Name, Define" and giving the area a name called "Staff." That didn't work either. I then changed the name of the sheet to "Staff." That worked. Apparently you have to have the sheet named what you want your table named, and you have to have the area defined in your spreadsheet that defines the area. I was able to run a simple query selecting all the data. I used the same data as was used for the text ODBC (see Figure 1) and the same query (changing the table name) and output (see Listing 4). The column names were properly retrieved. An interesting side effect is that the column names were returned in alphabetical order.

Formatting on the cells doesn't seem to matter, as the ODBC driver makes it's own decisions about the data. In the case of the zip code, Excel was informed that it contained text data. Yet when the data was returned from the query it clearly considered the zip code to be a number.

I then expanded the data by one column but didn't change the area defined by the name "Staff." The query still worked, but the additional data didn't appear. Only when I expanded the defined area to include the new column did the new information appear.

From all of this it was obvious that the sheet name is the table name, and you must have an area defined on your sheet that encompasses all the required data. As in the text ODBC, the first row is considered to contain the names of the columns for the data.

When defining the data source for Excel in the CF Administrator there's a field called "Rows to Scan." I have no idea what this field represents. I originally thought it was the maximum rows to be returned, but that's not what it does.

I should also point out that if the defined area contains blank rows, then they are also returned. The named area on the spreadsheet is whats always returned when doing the query. Writing to Excel

Now it was time to see how to write data to an Excel spreadsheet. I used the code shown in Listing 1 that was used in the text example. I changed the table name and removed the .txt extension. The code ran with no errors. Time to open the spreadsheet and see what happened.

The data appeared in the Excel spreadsheet as a sheet within the file. There was a new page in the file called "MyTable," which is the table name I created. There was also a named area in the spreadsheet called "MyTable" that exactly matched the amount of data that would have been created. This made sense, as that was the case when reading. The sheet name and the named area on the sheet need to be the same. The data that appeared is shown in Listing 2.

I ran the code again and an error was generated when creating the table. Since the table existed, this was reasonable. I removed the create table code to see what would happen and ran the script.

Another error was produced, informing me that I couldnt expand the named range. It seems that once the data has been inserted into the spreadsheet it can no longer be changed. You cant add to or update the data, and you cant delete the data unless you delete the table using the code shown in Listing 5.

It took 1.8 seconds to insert 500 rows into the Excel spreadsheet. This is considerably faster than writing to a text file.

What Good Is It?
By being able to create a text file I was able to create the data needed in Cold- Fusion Express, even though it doesn't support the <CFFILE> tag. It was slow and should be used in extreme cases, which this was. Using a text file as an ODBC source would allow the reading of data with CF Express. For the "real" version of ColdFusion, the <CFFILE> tag is the obvious choice.

The capability to write to an Excel spreadsheet could be useful. You could create data for a client in Excel format, then deliver the file using the <CFCONTENT> tag. By wrapping the table delete with a simple <CFTRY> and <CFCATCH> tag, the attempt to delete a nonexistent table could be easily handled.

Even then Id think it would be better to just create a text file with comma-delimited values, name the file with .CSV extension, and deliver it to the client if you wanted to create a single file only.

But consider if you need to deliver multiple files that are going to be imported into Excel. I think it would be better to create the multiple files using an Excel ODBC connection and create multiple tables (sheets) in a single Excel file, then transfer that file using <CFCONTENT>. The client will receive only a single file but with multiple sheets. This could be useful in some circumstances.

Wrapping It Up
The need to read from and write to text files using ColdFusion Express made me explore how to do so within it's limits. The ability to use an ODBC source pointing to the text file seemed to be the answer. The process does work; however, performance is fairly poor. But it can fill a need.

After finding out about the text ODBC capabilities, I decided to explore using Excel as a data source. It was possible and did work. The documentation I had for Excel was incorrect and some experimentation was required to find the solution. The information for text files as a source was not to be found. Now that I've written about this, I suppose someone will come forward and point me to it.

The process is so slow when writing the data, making it painful except for the smallest files and when no other solution is available. Even so, it was an interesting exploration into the capabilities and limitations of using text files and Excel as ODBC sources for ColdFusion.

More Stories By Ray Thompson

Ray Thompson is employed by Q Systems in Oak Ridge, Tennessee, a leading developer of Web-based applications. Ray has over 30 year's of experience in information systems and has been involved in many aspects of systems design, deployment, and management, ranging from "big iron" to desktops.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
SYS-CON Events announced today that Nirmata will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...