dbquery-mysql.c (2521B)
1 /* 2 Copyright (C) 2012, 2013 Tomas Hlavaty <tom@logand.com> 3 4 Permission is hereby granted, free of charge, to any person 5 obtaining a copy of this software and associated documentation 6 files (the "Software"), to deal in the Software without 7 restriction, including without limitation the rights to use, copy, 8 modify, merge, publish, distribute, sublicense, and/or sell copies 9 of the Software, and to permit persons to whom the Software is 10 furnished to do so, subject to the following conditions: 11 12 The above copyright notice and this permission notice shall be 13 included in all copies or substantial portions of the Software. 14 15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 19 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 20 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 22 DEALINGS IN THE SOFTWARE. 23 */ 24 25 #include <stdlib.h> 26 #include <string.h> 27 #include <stdio.h> 28 #include <stdarg.h> 29 #include <mysql/mysql.h> 30 31 void die(const char *format, ...); 32 void repl(); 33 34 static MYSQL *conn; 35 36 void query(char *q) { 37 if(mysql_query(conn, q)) die(0); 38 MYSQL_RES *z = mysql_store_result(conn); 39 int i, j; 40 MYSQL_FIELD *f; 41 printf("(("); 42 for(j = 0; (f = mysql_fetch_field(z)); j++) { 43 if(0 < j) printf(" "); 44 printf("\"%s\"", f->name); 45 } 46 printf(")\n ("); 47 mysql_field_seek(z, 0); 48 for(j = 0; (f = mysql_fetch_field(z)); j++) { 49 if(0 < j) printf(" "); 50 printf("%d", f->type); 51 } 52 printf(")"); 53 MYSQL_ROW r; 54 for(i = 0; (r = mysql_fetch_row(z)); i++) { 55 printf("\n ("); 56 mysql_field_seek(z, 0); 57 for(j = 0; (f = mysql_fetch_field(z)); j++) { 58 if(0 < j) printf(" "); 59 char *v = r[j]; 60 if(!v) 61 printf("NIL"); 62 else 63 switch(f->type) { 64 case 246: // float 65 case 8: printf("%s", v); break; // int 66 default: 67 printf("\"%s\"", v); 68 } 69 } 70 printf(")"); 71 } 72 printf(")\n"); 73 fflush(stdout); 74 mysql_free_result(z); 75 } 76 77 int main(int argc, char **argv) { 78 if(argc < 5) die("usage: %s host user password db [query]", argv[0]); 79 if(!(conn = mysql_init(NULL))) die(0); 80 if(!mysql_real_connect(conn, argv[1], argv[2], argv[3], argv[4], 0, NULL, 0)) 81 die(0); 82 if(argc < 6) repl(); else query(argv[5]); 83 return 0; 84 }