O'Reilly logo

Managing & Using MySQL, 2nd Edition by Hugh E. Williams, Randy Yarger, George Reese, Tim King

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding Symbols

Adding a new symbol to the database is simpler than a query in that you have no results to process, yet more complex in that you have more mucking around with memory allocation for strings in building the query. We take the same approach in building the insert that we took in building SELECT for get_stock( ) except that we do not bother calculating how much memory we need; 255 characters should be more than enough for this example. Nothing about adding the stock is new.

int assign_stock(Stock *stock) {
    char *query = "INSERT INTO Stock ( symbol, openPrice, \
                   currPrice, high52, low52 ) \
                   VALUES ('%s', %f, %f, %f, %f)";
    char *sql;
    int state;
  
    sql = (char *)malloc(255 * sizeof(char));
    error = (char *)NULL;
    sprintf(sql, query,
            stock->symbol, stock->open_price, stock->current_price,
            stock->high52, stock->low52);
    state = mysql_query(connection, sql);
    free(sql);
    if( state != 0 ) {
        error = mysql_error(connection);
        return -1;
    }
    return 0;
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required