Home  >  Article  >  Database  >  Ubuntu下用C语言访问MySQL数据库

Ubuntu下用C语言访问MySQL数据库

WBOY
WBOYOriginal
2016-06-07 16:56:301093browse

在Ubuntu下费了好长时间终于让C操作MySQL成功了,在此把方法记下来,留着以后用。先安装MySQL 代码: sudo apt-get install mysql

在Ubuntu下费了好长时间终于让C操作MySQL成功了,在此把方法记下来,留着以后用。先安装MySQL
代码:
sudo apt-get install mysql-server mysql-client

再装开发包
代码:
sudo apt-get install libmysqlclient15-dev

可以用以下代码测试一下
代码:
/* Simple C program that connects to MySQL Database server*/
#include
#include

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

   char *server = "localhost";
   char *user = "root";
   char *password = ""; /* 此处改成你的密码 */
   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);
}


编译:


方法一:gcc test.c -o test -I/user/include/mysql                               试了一下,提示找不到mysql.h。

我试了一下,提示找不到mysql.h。
分析:
/user/include/mysql:全是.h文件,应该应编译阶段
/user/lib/mysql:是静态库和动态库,,应该与上面的.h文件对应,用于连接阶段。

方法二:gcc test.c -o test -L/user/lib/mysql -lmysqlclient                成功!

方法三:gcc test.c -o test $(mysql_config --cflags) $(mysql_config --libs)

或者:gcc test.c -o test $(mysql_config --cflags --libs)                        成功!

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn