วันอาทิตย์ที่ 28 พฤศจิกายน พ.ศ. 2553

วิธีการ compile ภาษา C บน GCC ให้ใช้ Module ของ MySQL ได้

โค้ดนี้นะครับ

#include <mysql.h>
#include <stdio.h>

main() {
   MYSQL *conn;
   MYSQL_RES *res;
   MYSQL_ROW row;

   char *server = "localhost";
   char *user = "root";
   char *password = "mysqlpass"; /* set me first */
   char *database = "mysql";

   conn = mysql_init(NULL);

   /* Connect to database */
   if (!mysql_real_connect(conn, server,
         user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   /* send SQL query */
   if (mysql_query(conn, "show tables")) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   res = mysql_use_result(conn);

   /* output table name */
   printf("MySQL Tables in mysql database:\n");
   while ((row = mysql_fetch_row(res)) != NULL)
      printf("%s \n", row[0]);

   /* close connection */
   mysql_free_result(res);
   mysql_close(conn);
}


ถ้าคอมไพล์ไปตรงๆเกิด Error ชัวร์ จะขึ้นประมาณนี้

mysql.c:1:19: error: mysql.h: No such file or directory
mysql.c: In function ‘main’:
mysql.c:5: error: ‘MYSQL’ undeclared (first use in this function)
mysql.c:5: error: (Each undeclared identifier is reported only once
mysql.c:5: error: for each function it appears in.)
mysql.c:5: error: ‘conn’ undeclared (first use in this function)
mysql.c:6: error: ‘MYSQL_RES’ undeclared (first use in this function)
mysql.c:6: error: ‘res’ undeclared (first use in this function)
mysql.c:7: error: ‘MYSQL_ROW’ undeclared (first use in this function)
mysql.c:7: error: expected ‘;’ before ‘row’
mysql.c:20: warning: incompatible implicit declaration of built-in function ‘exit’
mysql.c:26: warning: incompatible implicit declaration of built-in function ‘exit’
mysql.c:33: error: ‘row’ undeclared (first use in this function)


แน่นอนว่า ไม่มี libmysqlclient15-dev ครับ ให้ install เสีย

sudo apt-get install libmysqlclient15-dev

 แล้วจัดการคอมไพล์

$ gcc -o learn  -L/usr/lib/mysql -lmysqlclient learn.c

จบข่าว 

ไม่มีความคิดเห็น:

แสดงความคิดเห็น