Guest User

Untitled

a guest
Jan 17th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #include"sqlite3.h"
  5.  
  6. int main(int argc, char *argv[]){
  7. sqlite3 *database_connection; //initialize connection handle
  8. sqlite3_stmt *database_statement; //initialize statement variable
  9. char query[101] = {0};
  10. int error = 0; //initialize error indicator
  11.  
  12. if(argc != 2){ //arguments == 1 ? (database name)
  13. fprintf(stderr,"error: invalid number of parameters\n");
  14. return 1;
  15. }
  16.  
  17. error = sqlite3_open(argv[1], &database_connection); //open or create requested database
  18. if(error){
  19. fprintf(stderr,"error: could not open file\n");
  20. return 1;
  21. }
  22.  
  23. strcpy(query, "CREATE TABLE IF NOT EXISTS stock (product_name TEXT PRIMARY KEY, product_count INTEGER DEFAULT 0)"); //prepare sql command: CREATE TABLE
  24. error = sqlite3_exec(database_connection, query, 0, 0, 0); //execute prepared command
  25. if(error){
  26. fprintf(stderr,"error: could not create stock table\n");
  27. return 1;
  28. }
  29.  
  30. char command[21] = {0}; //initialize array for commands
  31. char product_name[21] = {0}; //initialize array for product names
  32.  
  33. printf("> ");
  34. scanf("%20s", command);
  35.  
  36. if(command[0] == '\0'){
  37. fprintf(stderr, "error: invalid command");
  38. return 1;
  39. }
  40.  
  41. if(!strcmp(command, "NOVY")){ //received "NOVY"
  42. if(!scanf("%20s", product_name)){ //invalid product name received
  43. fprintf(stderr, "error: invalid product name");
  44. return 1;
  45. }
  46. //sprintf(query, "SELECT product_name FROM stock WHERE product_name = %s", product_name); //prepare sql command: SELECT to check whether requested already product exists
  47. sprintf(query, "INSERT INTO stock VALUES(%s, 0)", product_name);
  48. //printf("debug: query = %s\n", query);
  49. error = sqlite3_prepare_v2(database_connection, query, -1, &database_statement, NULL);
  50. if(error){
  51. printf("sqlite prepare error: %d\n", error);
  52. fprintf(stderr,"error: could not prepare operation SELECT product_name -0\n");
  53. return 1;
  54. }
  55. }
  56. return 0;
  57. }
Add Comment
Please, Sign In to add comment