C Realize reading SQL file in batch to generate SQL statements

txt text content:

/*data.txt*/

1 2 3
2 3 3
3 4 4
4 5 4

The desired statement:

--data_out.sql

INSERT INTO XXX VALUES('1','2','3');
INSERT INTO XXX VALUES('2','3','3');
INSERT INTO XXX VALUES('3','4','4');
INSERT INTO XXX VALUES('4','5','4');

Code:

The variables contained can be changed according to your needs.

#include <stdio.h>
#include <string.h>
#define MAXLEN 1000
char ln[MAXLEN];
FILE *f,*fout;
int n,L;
char d1[30],d2[30],d3[30];
int main() {
    f=fopen("data.txt","r");
    fout=fopen("data_out.sql","w");
    if (NULL==f) {
        printf("Can not open file!\n");
        return 2;
    }
    n=0;
    while (1) {
        if (NULL==fgets(ln,MAXLEN,f)) break;
        L=strlen(ln);
        if ('\n'==ln[L-1]) {
            n++;
            if (3!=sscanf(ln,"%s%s%s",d1,d2,d3)) {
                printf("line %d:[%s] can not read 3 double numbers!\n",n,ln);
                break;
            } else {
                //use d1,d2,d3 of line n
                //fprintf(fout,"SELECT * from XXX where XX='%s' and XX='%s' and '%s' order by XX\n",d1,d2,d3);
                fprintf(fout,"INSERT INTO XXX VALUES('%s','%s','%s');\n",d1,d2,d3); 
            }
        }
    }
    fclose(f);
    fclose(fout);
    return 0;
}

 

Published 108 original articles · praised 48 · 50,000+ views

Guess you like

Origin blog.csdn.net/larry1648637120/article/details/102573103