Here's some code I wrote this evening, gearing up for my bigger MySQL driver application.
I'm writing a driver to read in a series of SQL statements from a text file, parse them using a semicolon as a delimiter, and then identifying them as either a SELECT clause or not.
It works fine right now. I'm putting it out here for a critique and to learn better practices.
If you have the time, I would appreciate your feedback. Here's the code and a small input file to test with.
Input file. Lines starting with "--" are comment lines.Code:#include <stdio.h> #include <string.h> #include <stdlib.h> #define FILENAME "/Users/toddburch/Desktop/sql.txt" char * readSQL(FILE * fp) { // File is already open char buffer[32000] = {0} ; // SQL statement buffer - assume it's big enough char line[81] = {0} ; // fgets buffer char * ptr ; char * end_of_line ; // Read data from the input file until a semicolon is found or end of file is hit while (fgets(line, sizeof(line), fp) ) { if ( strncmp(line, "--", 2) == 0 ) continue ; // skip comments if ( (end_of_line = strrchr(line, '\n')) != NULL ) *end_of_line = 0 ; // Remove newline if ( (end_of_line = strrchr(line, '\r')) != NULL ) *end_of_line = 0 ; // Remove cr ptr = line ; while (*ptr == ' ') ptr++ ; // index past leading blanks if (strlen(ptr) == 0) continue ; // look for trailing semi colon - that terminates a statement end_of_line = ptr + strlen(ptr)-1 ; // position to last character while (*end_of_line == ' ') *end_of_line-- = 0 ; // back up to last non-blank if (*end_of_line == ';') { strcat(buffer, ptr) ; // append to buffer break ; } else { strcat(buffer, ptr) ; // append to buffer strcat(buffer, " ") ; // separate it } } if ( strlen(buffer) == 0 ) return NULL ; // get some storage and pass back a pointer to it ptr = malloc(strlen(buffer)+1) ; if (!ptr) return NULL ; strcpy(ptr,buffer) ; return ptr ; } int isSelect(char * sql) { // Determine if this is a SELECT statement char word[] = "SELECT" ; int i ; if (strlen(sql) < 7) return 0 ; // no match for (i = 0 ; i < 6 ; i++ ) if ( word[i] != toupper(sql[i]) ) return 0 ; // no match return 1 ; // match } int main (int argc, const char * argv[]) { FILE * fp ; char * sql ; fp = fopen(FILENAME , "r") ; if (!fp) { printf("cannot open input file " FILENAME "\n") ; return -1 ; } while (1) { sql = readSQL(fp) ; if (!sql) break ; if (isSelect(sql)) printf("Select Statement!\n") ; else printf("Not a select Statement!\n") ; printf("SQL = >%s<\n\n", sql) ; free(sql) ; } fclose(fp) ; return 0; }
I'm not validating SQL, just splitting the input into individual statements.Code:select * from table where (col1 = 5 ) ; -- this is a comment -- insert into table values (1, ';') ; select name, age, sex, phone from othertable order by -- age -- sex name; --
Thanks, Todd



LinkBack URL
About LinkBacks



