Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL command parse question 1

Status
Not open for further replies.

sarzi

Programmer
Feb 25, 2004
3
US
I need to parse a SQL command for my project using C.
The whole sql command is inputed as a string and the function should create a token list that contains all the components of the commands.

EX: "create table tab1(name char(10), id int)"
should have the token list as "create->table->tab1->(->name->char->( ->10 -> )->,->id-> int"

I try to use strtok(*command, " ")to parse it. however, it doesnot put "(", ")", "," into seperate tokens. The output becomes create->table->tab1(name->char(10),->id-> int"

can anyone help me? Thanks!
 
It depends on where you're going with this.

If you're just after a few simple commands, then a simple hand-rolled parser will probably suffice.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

void parse ( const char string[], char token[] ) {
  static const char *prev;
  int len;
  if ( string != NULL ) prev = string;

  token[0] = '\0';  /* no result so far */

  /* skip whitespace */
  while ( *prev && isspace(*prev) ) prev++;
  if ( *prev == '\0' ) return;

  if ( isalpha(*prev) ) {
    /* an identifier */
    sscanf( prev, "%[A-Za-z0-9]%n", token, &len );
    prev += len;
  } else
  if ( isdigit(*prev) ) {
    /* an integer */
    sscanf( prev, "%[0-9]%n", token, &len );
    prev += len;
  } else {
    /* punctuation - assuming single letter */
    token[0] = *prev++;
    token[1] = '\0';
  }
}

int main ( ) {
  char test[] = "create table tab1(name char(10), id int)";
  char token[100];
  for ( parse(test,token) ; token[0] != '\0' ; parse(NULL,token) ) {
    printf("Token=%s\n", token );
  }
  return 0;
}

If on the other hand you're looking to parse a substantial chunk of SQL in all its variety, then perhaps lex/yacc (or GNU flex/bison) should be considered.
Once you're over the initial learning curve, its fairly easy to generate a parser. With a little more care, you can construct the evaluation tree inside the parser as it goes.


--
 
use boost lybraries (from boost.org) to deal with regular expressions

Ion Filipski
1c.bmp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top