Thread: How to copy value from MySQL result to string pointer?

  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
    28,413
    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).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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, 09: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, 11:06 PM