Guest User

Untitled

a guest
Sep 10th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. Return a result from a MySQL query in a function after closing connection in C
  2. int CheckBox(char *mac)
  3. {
  4. MYSQL *conn;
  5. MYSQL_RES *res;
  6. MYSQL_ROW row;
  7.  
  8. /* database details */
  9. char *server = "localhost";
  10. char *user = "user";
  11. char *password = "pw";
  12. char *database = "db";
  13. int retvalue;
  14.  
  15. conn = mysql_init(NULL);
  16.  
  17. /* connect to database */
  18. if (!mysql_real_connect(conn, server,user, password, database, 0, NULL, 0))
  19. {
  20. fprintf(stderr, "%sn", mysql_error(conn));
  21. exit(1);
  22. }
  23.  
  24. /* create and send SQL query */
  25. char query[1600];
  26. sprintf(query,"SELECT * FROM boxes WHERE mac = '%s'", mac);
  27. if (mysql_query(conn, query))
  28. {
  29. fprintf(stderr, "%sn", mysql_error(conn));
  30. exit(1);
  31. }
  32.  
  33. res = mysql_use_result(conn);
  34. /* check result to see if we have a hit */
  35. if ((row = mysql_fetch_row(res)) != NULL)
  36. {
  37.  
  38. printf("mac (%s) did exist with id %s.n",mac,(char *)row[0]);
  39. retvalue = (int)row[0];
  40. } else
  41. {
  42. printf("mac (%s) did NOT exist ",mac);
  43. /* mac address did not yet exist, so create it */
  44. sprintf(query,"INSERT INTO boxes (mac) VALUES ('%s')",mac);
  45. if (mysql_query(conn, query))
  46. {
  47. fprintf(stderr, "%sn", mysql_error(conn));
  48. exit(1);
  49. } else
  50. {
  51. printf("but now doesn");
  52. CheckBox(mac);
  53. }
  54. }
  55.  
  56. /* close connection */
  57. mysql_free_result(res);
  58. mysql_close(conn);
  59.  
  60. /* return id number of box */
  61. return retvalue;
  62. }
Add Comment
Please, Sign In to add comment