views:

54

answers:

1

I'm writing a program, in C++, to access tables in MySQL via the MySql C++ Connector.

I retrieve a record from the User (via GUI or Xml file).

Here are my questions:

  1. Should I search the table first for the given record, then append if it doesn't exist,

  2. Or append the record, and let MySQL append the record if it is unique?

Here is my example table:

mysql> describe ing_titles;
+----------+----------+------+-----+---------+-------+
| Field    | Type     | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| ID_Title | int(11)  | NO   | PRI | NULL    |       |
| Title    | char(32) | NO   |     | NULL    |       |
+----------+----------+------+-----+---------+-------+

In judgment, I am looking for a solution that will enable my program to respond quickly to the User.

During development, I have small tables (less than 5 records), but I am expecting them to grow when I formally release the application.

FYI: I am using Visual Studion 2008, C++, wxWidgets, and MySQL C++ Connector on Windows XP and Vista.

+1  A: 

Mark the field in question with a UNIQUE constraint and use INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE.

The former will update the records if they already exists, the latter will just do nothing.

Searching the table first is not efficient, since it requires two roundtrips to the server: the first one to search, the second one to insert (or to update).

The syntaxes above do the same in one sentence.

Quassnoi
See edited question (I added table description). Will the `UNIQUE` still work for the `Title` field?
Thomas Matthews
@Thomas: which field contains the value you want to search for?
Quassnoi
@Thomas: if you want the titles to be unique, issue this: `CREATE UNIQUE INDEX ux_ingtitles_title ON ing_titles (title)`
Quassnoi
After I get input from User, I want to search by `Title`, to see if the record exists. I won't know what the ID field is (for an existing title), so I can't search by ID.
Thomas Matthews