Search code examples
mysqlcmysql-error-1064

MYSQL API in C - linux


I can't get the following code to work. It's working with normal select or insert, but when I try to insert a variable to it it didn't work. Can some let me know please what's wrong here?

Please note that the output is below.

int main(int argc, char **argv)
{

  MYSQL *conn;
  char str[100] = "test";
  conn = mysql_init(NULL);

  char stmt_buf[100];
  sprintf (stmt_buf, "insert into test values ('%s')", str);

  printf("\n%s\n",stmt_buf);

  mysql_query (conn, stmt_buf);
  mysql_close(conn);
  return 0;
}

~$./version

insert into test values ('test')
Segmentation fault

Solution

  • I didn't see you are connected to database by mysql_real_connect also there is no mysql_select_db and mysql_exec_sql call.

    Here is an example for you.

    int main(int argc, char **argv)
    {
        MYSQL mysql;
        char stmt_buf[100];
        if (mysql_init(&mysql) == NULL) {
            printf("Can not initialize");
            exit(1);
        }
        if (!mysql_real_connect
            (&mysql, "localhost", "USERNAME", "PASSWORD", NULL, 0, NULL, 0)) {
            mysql_error(&mysql);
            exit(1);
        }
    
        if (mysql_select_db(&mysql, "DATABASENAME")) {
            mysql_error(&mysql);
            exit(1);
        }
    
        sprintf(stmt_buf, "insert into test values ('%s')", "test");
    
        if (mysql_exec_sql(&mysql, stmt_buf))
            mysql_error(&mysql));
    
        mysql_close(&mysql);
    }