How to copy value from MySQL result to string pointer?

This is a discussion on How to copy value from MySQL result to string pointer? within the C Programming forums, part of the General Programming Boards category; Hi I'm trying to copy a value from a MySQL query result to a string pointer with no success. As ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    7

    How to copy value from MySQL result to string pointer?

    Hi
    I'm trying to copy a value from a MySQL query result to a string pointer with no success. As soon as I call "mysql_free_result" my variable is empty! If I print the variable before "mysql_free_result" it is there! Here is a snippet of my code:

    Code:
    /* connect to db here */
    char *name;
    
    if (mysql_query(conn, "SELECT firstname FROM employees WHERE id = 8") != 0) {
            fprintf(stderr, "%s\n", mysql_error(conn));
            } else {
            res = mysql_use_result(conn);
                    if ((row = mysql_fetch_row(res)) != NULL) {
                    name = row[0];
                    mysql_free_result(res);
                    printf("%s\n",name);
    }
    mysql_close(conn);
    I don't quite understand how to copy the value to "name". I guess "name" is pointing to something that does not exist after "mysql_free_result". How do I keep the value in "name"?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,310
    You would need to allocate space for the string, say with malloc(), and then copy over the characters, say with strncpy() or strcpy(). Presumably the MySQL API gives you some way of determining the length of the string so you can allocate space (e.g., it might just be a null terminated string, so strlen() would do).
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    7
    Thanks!
    It worked well!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM
  2. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM
  3. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 10:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21