Handling Character Strings
- Method 1: Use char[] (a char string), which is the most common method for processing character data in C programs.
EXEC SQL BEGIN DECLARE SECTION; char str[50]; EXEC SQL END DECLARE SECTION;Note that you have to take care of the length yourself. If you use this host variable as the target variable of a query which returns a string with more than 49 characters, a buffer overflow occurs.
- Method 2: Use the VARCHAR type, which is a special type provided by ecpg. The definition on an array of type VARCHAR is converted into a named struct for every variable. The statement is as follows:
VARCHAR var[180];
It will be converted into:
struct varchar_var { int len; char arr[180]; } var;To store a string in a VARCHAR host variable, the host variable has to be declared as a string including the zero-byte terminator. arr stores the string including a terminating zero byte. len stores the length of the string stored in arr without the terminating zero byte. The terminator is not included when the length is calculated. When a host variable is used as input for a query, if the values of strlen(arr) and len are different, the shorter one is used.
- VARCHAR can be written in upper or lower case, but not in mixed case.
- char and VARCHAR host variables can also hold values of other SQL types, which will be stored in their string forms.