dbquery-sqlite.c (2396B)
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 <stdio.h> 26 #include <sqlite3.h> 27 28 void die(const char *format, ...); 29 void repl(); 30 31 static sqlite3 *conn; 32 33 void query(char *q) { 34 sqlite3_stmt *z; 35 if(sqlite3_prepare_v2(conn, q, -1, &z, 0)) die("error: sqlite3_prepare_v2 failed"); 36 int i, j, m = sqlite3_column_count(z); 37 printf("(("); 38 for(j = 0; j < m; j++) { 39 if(0 < j) printf(" "); 40 printf("\"%s\"", sqlite3_column_name(z, j)); 41 } 42 printf(")\n ("); 43 for(j = 0; j < m; j++) { 44 if(0 < j) printf(" "); 45 printf("%d", sqlite3_column_type(z, j)); 46 } 47 printf(")"); 48 for(i = 0; SQLITE_ROW == sqlite3_step(z); i++) { 49 printf("\n ("); 50 for(j = 0; j < m; j++) { 51 if(0 < j) printf(" "); 52 if(!sqlite3_column_text(z, j)) 53 printf("NIL"); 54 else 55 switch(sqlite3_column_type(z, j)) { 56 // case 246: // float 57 case 5: printf("%d", sqlite3_column_int(z, j)); break; // int 58 default: 59 printf("\"%s\"", sqlite3_column_text(z, j)); 60 } 61 } 62 printf(")"); 63 } 64 printf(")\n"); 65 fflush(stdout); 66 sqlite3_finalize(z); 67 } 68 69 int main(int argc, char **argv) { 70 if(argc < 2) die("usage: %s db [query]", argv[0]); 71 if(sqlite3_open(argv[1], &conn)) die("error: sqlite3_open failed"); 72 if(argc < 3) repl(); else query(argv[2]); 73 return 0; 74 }