[MySQL C API] 6. 컬럼 이름 가져오기(Column header)
1. 소스코드
이전에는 result set으로 테이블을 받아와 한 row씩 데이터를 출력했었다.
이것은 테이블에 저장된 값들만 가지고 왔을 뿐, Column 정보는 알 수 없었다.
이전 글 링크 : http://dk-projects.tistory.com/11
이 소스코드에서는 column header를 사용해서
Column의 이름들을 출력해 본다.
#include <my_global.h>
#include <mysql.h>
void finish_with_error(MYSQL *con)
{
fprintf(stderr, "%s \n", mysql_error(con));
mysql_close(con);
exit(1);
}
int main(int argc, char **argv)
{
MYSQL *con = mysql_init(NULL);
if (con == NULL) {
fprintf(stderr, "mysql_init() failed \n");
exit(1);
}
if (mysql_real_connect(con, "localhost", "user01", "1q2w3e!", "testdb",
0, NULL, 0) == NULL)
{
finish_with_error(con);
}
if (mysql_query(con, "SELECT * FROM Cars LIMIT 3")) {
finish_with_error(con);
}
MYSQL_RES *result = mysql_store_result(con);
if (result == NULL) {
finish_with_error(con);
}
int num_fields = mysql_num_fields(result);
MYSQL_ROW row;
// field 정보를 저장하는 MYSQL_FIELD구조체 포인터 선언
MYSQL_FIELD *field;
while((row = mysql_fetch_row(result)))
{
for(int i = 0; i < num_fields; i++) {
if (i == 0) {
// Column 영역이름 출력
while(field = mysql_fetch_field(result))
{
printf("%s ", field->name);
}
printf("\n");
}
// row 반복하여 출력
printf("%s ", row[i] ? row[i] : "NULL");
}
}
printf("\n");
mysql_free_result(result);
mysql_close(con);
exit(0);
}
MYSQL_FIELD 구조체에는
필드의 이름, 타입, 사이즈 같은 필드에 관한 정보만 저장되어 있다.
필드 값(데이터)은 이 구조체에 저장되는 것이 아니라,
MYSQL_ROW 구조체에 저장된다는 차이를 알 수 있다.
2. 출력 예시
$ ./headers
Id Name Price
1 Hyundai 8000
2 Audi 9000
아래 링크를 참고하여 번역 및 수정함
http://zetcode.com/db/mysqlc/