MySQL- Руководство разработчика



              

Пример простого встроенного сервера - часть 2


void die(MYSQL *db, char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); putc('\n', stderr); if (db) db_disconnect(db); exit(EXIT_FAILURE); }

MYSQL * db_connect(const char *dbname) { MYSQL *db = mysql_init(NULL); if (!db) die(db, "mysql_init failed: no memory"); mysql_options(db, MYSQL_READ_DEFAULT_GROUP, "simple"); if (!mysql_real_connect(db, NULL, NULL, NULL, dbname, 0, NULL, 0)) die(db, "mysql_real_connect failed: %s", mysql_error(db)); return db; }

void db_disconnect(MYSQL *db) { mysql_close(db); }

/* * show_query: this code is snagged from mysql.cc; this function * is intended to be used internally to db_do_query() */ static char * show_query(MYSQL *db) { MYSQL_RES *res; MYSQL_FIELD *field; MYSQL_ROW row; char sep[256], *psep = sep; char *is_num = 0; char *err = 0; unsigned int length = 1; /* initial "|" */ unsigned int off;

if (!(res = mysql_store_result(db))) return mysql_error(db); if (!(is_num = malloc(mysql_num_fields(res)))) { err = "Не хватило памяти"; goto err; } /* set up */ *psep++ = '+'; while ((field = mysql_fetch_field(res))) { unsigned int len = strlen(field->name); if (len < field->max_length) len = field->max_length; if (len < 2 && !IS_NOT_NULL(field->flags)) len = 2; /* \N */ field->max_length = len + 1; /* bending the API... */ len += 2; length += len + 1; /* " " before, " |" after */ if (length >= 255) { err = "row too long"; goto err; } memset(psep, '-', len); psep += len; *psep++ = '+'; *psep = '\0'; } /* column headings */ puts(sep); mysql_field_seek(res,0); fputc('|',stdout); for (off=0; (field = mysql_fetch_field(res)) ; off++) { printf(" %-*s|",field->max_length, field->name); is_num[off]= IS_NUM(field->type); } fputc('\n',stdout); puts(sep); /* rows */ while ((row = mysql_fetch_row(res))) { (void) fputs("|",stdout); mysql_field_seek(res,0); for (off=0; off < mysql_num_fields(res); off++) { field = mysql_fetch_field(res); printf(is_num[off] ? "%*s |" : " %-*s|", field->max_length, row[off] ? (char*) row[off] : "NULL"); } (void) fputc('\n',stdout); } puts(sep); err: if (is_num) free(is_num); mysql_free_result(res); return err; }




Содержание  Назад  Вперед