| 2 | |
| 3 | Example: |
| 4 | |
| 5 | {{{ |
| 6 | #include <stdio.h> |
| 7 | #include <mysql.h> |
| 8 | |
| 9 | int main(int argc, char* argv[]) |
| 10 | { |
| 11 | MYSQL* conn; |
| 12 | MYSQL_RES* res; |
| 13 | MYSQL_ROW row; |
| 14 | |
| 15 | const char* server = "192.168.1.106"; |
| 16 | const char* user = "pi"; |
| 17 | // const char* password = "mysql848"; |
| 18 | const char* password = "raspberry"; |
| 19 | const char* database = "test"; |
| 20 | const char* query = "SELECT * FROM abc;"; |
| 21 | |
| 22 | if(argc > 1) |
| 23 | server = argv[1]; |
| 24 | if(argc > 2) |
| 25 | user = argv[2]; |
| 26 | if(argc > 3) |
| 27 | password = argv[3]; |
| 28 | if(argc > 4) |
| 29 | database = argv[4]; |
| 30 | if(argc > 5) |
| 31 | query = argv[5]; |
| 32 | |
| 33 | printf("**srv [%s] user [%s] pass [%s] db [%s] q [%s]\n", server, user, password, database, query); |
| 34 | |
| 35 | conn = mysql_init(NULL); |
| 36 | |
| 37 | if(!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) |
| 38 | { |
| 39 | printf("Error connecting to DB: %s\n", mysql_error(conn)); |
| 40 | return 0; |
| 41 | } |
| 42 | |
| 43 | printf("***\n"); |
| 44 | |
| 45 | if(mysql_query(conn, query)) |
| 46 | { |
| 47 | printf("Error query: %s\n", mysql_error(conn)); |
| 48 | return 0; |
| 49 | } |
| 50 | |
| 51 | //printf("query success\n"); |
| 52 | |
| 53 | int rows_affected = (int) mysql_affected_rows(conn); |
| 54 | |
| 55 | printf("affected %d\n", rows_affected); |
| 56 | |
| 57 | if(rows_affected < 1) // select, show |
| 58 | { |
| 59 | res = mysql_use_result(conn); |
| 60 | //printf("rows %d filuelds %d eof %d\n", res->row_count, res->field_count, res->eof); |
| 61 | |
| 62 | int cnt = 0, i; |
| 63 | |
| 64 | while((row = mysql_fetch_row(res)) != NULL) |
| 65 | { |
| 66 | cnt++; |
| 67 | if(cnt == 1) |
| 68 | { |
| 69 | for(i = 0; i < (int)res->field_count; i++) |
| 70 | { |
| 71 | |
| 72 | if(i > 50) |
| 73 | break; |
| 74 | printf("%s,", res->fields[i].name); |
| 75 | } |
| 76 | printf("\n"); |
| 77 | |
| 78 | } |
| 79 | if(cnt > 10000) |
| 80 | break; |
| 81 | //printf("%d ", cnt); |
| 82 | for(i = 0; i < (int)res->field_count; i++) |
| 83 | { |
| 84 | |
| 85 | if(i > 50) |
| 86 | break; |
| 87 | printf("%s,", row[i]); |
| 88 | } |
| 89 | printf("\n"); |
| 90 | } |
| 91 | mysql_free_result(res); |
| 92 | } |
| 93 | mysql_close(conn); |
| 94 | |
| 95 | return 0; |
| 96 | } |
| 97 | |
| 98 | }}} |