Writing defensive SQL inserts.

Lessons learned Add comments

This post is filed under a new category named "Lessons Learned". This category will contain posts ranging from the "I can't believe you didn't know that!" to the "I had the same problem." to the "Ah, that's nice to know." kind of posts. Anyway, I hope it helps people out.

OK, I'm a very lazy programmer. So the less work I have typing, the more I like it. Today I was actually faced with my (programming) lazyness when a customer sent us a bug report.

We made an e-learning app some months ago for the Belgian Post that uses a lot of database access. Part of the database traffic is generated by a function that logs page visits. All went well untill today, the bug report was sent, saying there was an error inserting the log in the database. After looking at the error message the ASP page had generated, it was clear that something must have been changed to the database structure.

The insert query I used only specified the name of the log table, no fields, and the data to insert. Something like this...

CODE:
  1. INSERT INTO log VALUES('a', 'b', 'c')

I didn't think it was necessary to specify the columns to insert since all columns were going to be filled.

Without knowing, the server admin had set up a second database to do some kind of mirroring (I'm no database expert!). This action required all tables in the database to have an extra, invisible, field. Well that field actually caused the trouble with the insert query.

In order to get it fixed, all I had to do was specify the columns in the insert query.

CODE:
  1. INSERT INTO log(username, action, datetime) VALUES('a', 'b', 'c')

Lesson learned?
Always specify columns in an insert clause, even if the query would work without them!


Add to Bloglines - Digg This! - del.icio.us - Stumble It! - Twit This! - Technorati links - Share on Facebook - Feedburner
 

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Login