C   75
linux unix connect mysql c api program
Guest on 21st April 2022 01:14:10 AM


  1. /*
  2. See url for more info:
  3. http://www.cyberciti.biz/tips/linux-unix-connect-mysql-c-api-program.html
  4.  
  5. */
  6. #include <mysql.h>
  7. #include <stdio.h>
  8.  
  9. int main(void) {
  10.    MYSQL *conn;
  11.    MYSQL_RES *res;
  12.    MYSQL_ROW row;
  13.   /* Change me */
  14.    char *server = "localhost";
  15.    char *user = "root";
  16.    char *password = "PASSWORD";
  17.    char *database = "mysql";
  18.    
  19.    conn = mysql_init(NULL);
  20.    
  21.    /* Connect to database */
  22.    if (!mysql_real_connect(conn, server,
  23.          user, password, database, 0, NULL, 0)) {
  24.       fprintf(stderr, "%s\n", mysql_error(conn));
  25.       exit(1);
  26.    }
  27.  
  28.    /* send SQL query */
  29.    if (mysql_query(conn, "show tables")) {
  30.       fprintf(stderr, "%s\n", mysql_error(conn));
  31.       exit(1);
  32.    }
  33.  
  34.    res = mysql_use_result(conn);
  35.    
  36.    /* output table name */
  37.    printf("MySQL Tables in mysql database:\n");
  38.    while ((row = mysql_fetch_row(res)) != NULL)
  39.       printf("%s \n", row[0]);
  40.  
  41.    /* close connection */
  42.    mysql_free_result(res);
  43.    mysql_close(conn);
  44.  
  45.   return 0;
  46. }

Raw Paste

Login or Register to edit or fork this paste. It's free.