Problems with CRUD using MySQL

0

I'm trying to create a simple CRUD, but I'm having problems with the query method.

I wanted the method to display the following: Name, enrollment, course, phone and email in the first row and below the tuples information one by one in an organized way.

But it displays the information totally disorganized, a tuple is occupying more than one line, and the names of the columns in the table do not appear correctly: >IusingCodeBlocks17.12withtheGNUcompiler

Universitydatabasetables:

createtablealuno(nomevarchar(100)notnull,matriculaint,cursovarchar(50)notnull,telefonevarchar(20)notnull,emailvarchar(75),primarykey(matricula));createtableprofessor(nomevarchar(100)notnull,matriculaint,disciplinavarchar(50)notnull,telefonevarchar(20)notnull,emailvarchar(75),primarykey(matricula));

Globalvariables,includeanddefine:

#include<stdio.h>#include<windows.h>#include<winsock2.h>#include<mysql.h>#include<string.h>#defineNOME100#defineCURSO40#defineTEL20#defineEMAIL75MYSQLconexao;intstatusConexao;charquery[100];

Methods(Iputonlythosethatinvolvetheproblem):

voidcadastroAluno(void){mysql_init(&conexao);charnome[NOME];intmatricula;charcurso[CURSO];chartelefone[TEL];chareMail[EMAIL];system("cls");
printf("Cadastro de alunos\n\n");
setbuf(stdin,NULL);

printf("Digite o nome:");
fgets(nome,NOME,stdin);
nome[strcspn(nome,"\n")] = 0;

printf("Digite a matricula:");
scanf("%d",&matricula);

setbuf(stdin,NULL);

printf("Digite o curso:");
fgets(curso,CURSO,stdin);
curso[strcspn(curso,"\n")] = 0;

setbuf(stdin,NULL);

printf("Digite o telefone:");
fgets(telefone,TEL,stdin);
telefone[strcspn(curso,"\n")] = 0;

setbuf(stdin,NULL);

printf("Digite o e-mail:");
fgets(eMail,EMAIL,stdin);
eMail[strcspn(eMail,"\n")] = 0;

setbuf(stdin,NULL);


    if(mysql_real_connect(&conexao,"localhost", "root", "", "universidade", 3306, NULL, 0)){

        sprintf(query,"INSERT INTO aluno(nome,matricula,curso,telefone,email) values('%s','%d','%s','%s','%s');",nome,matricula,curso,telefone,eMail);

       statusConexao = mysql_query(&conexao,query);

       if(!statusConexao){
            printf("Cadastro concluído com sucesso\nLinhas afetadas:%d\n",mysql_affected_rows(&conexao));
       }else{
            printf("Falha no cadastro.Tente novamente\n");
       }
       system("PAUSE");
       mysql_close(&conexao);

    }else{

        printf("Falha na conexão ao banco de dados\n");
        printf("Erro %d: %s\n", mysql_errno(&conexao), mysql_error(&conexao));

    }

 }
void consultaAlunoSim(void){

system("cls");
mysql_init(&conexao);
MYSQL_RES * resp;
MYSQL_ROW linhas;
MYSQL_FIELD * campos;
int contador;
char querySimples[] = "SELECT * FROM aluno;";

if(mysql_real_connect(&conexao, "localhost", "root", "", "universidade", 3306, NULL, 0)){

    if(mysql_query(&conexao,querySimples)){
        printf("Erro: %s\n:",mysql_error(&conexao));
    }else{

        resp = mysql_store_result(&conexao);

        if(resp){

            campos = mysql_fetch_field(resp);

            for(contador = 0; contador < mysql_num_fields(resp); contador++){
                printf("%s",(campos[contador].name));

                if(mysql_num_fields(resp) > 1){
                    printf("\t");
                }

            }

            printf("\n");

            while((linhas = mysql_fetch_row(resp))!= NULL){

                for(contador = 0; contador < mysql_num_fields(resp); contador++){
                    printf("%s\t",linhas[contador]);
                }
                printf("\n");

            }
        }

        system("PAUSE");
        mysql_free_result(resp);
        mysql_close(&conexao);

    }

}else{
    printf("Falha na conexão ao banco de dados\n");
    printf("Erro %d : %s\n",mysql_errno(&conexao),mysql_error(&conexao));
  }

}
    
asked by anonymous 18.06.2018 / 02:40

1 answer

1

As for the problem you've detected yourself, it's just a matter of output formatting - the C compiler will not invent a way to abbreviate a 40 character "José dos Santos Pereira" name in a column of just over 6 characters "name". You have to make some sophisticated code to leave a space appropriate for the width of the columns, and possibly abbreviate the content of columns that are larger - That is, in possession of the query results, check the maximum "name" size and add an appropriate number of spaces after the word "name" at the top of the column. And also create a way to align the results in the other columns - if a name has 20 characters, and the second row has 30 characters, the second column (enrollment) can only have its values printed from column 31. You are using the tab character ( \t ) that does this magic - but only for fields that vary up to 7 characters in length. The tab is at most equal to 8 spaces wide.

In fact, showing well-formatted data in a text terminal is far from being a simpler task, and the use of C language, which is a comparatively low-level language , to manipulate textual data does not help.

For comparison, the link below is for a Python code that does this - it displays tabular results in the terminal - it's the part of the application that does just that, the data itself is passed as parameters from other points in the same application - this is a more sophisticated "production" application that can draw frames around the columns, etc ... and even it does not have a mechanism to abbreviate the size of the data in the columns. But there is every part that would be needed in your code to calculate the width of each column before printing the table, etc ...

link

In short - it's cool for you to play around with your learning code - but if you are really developing an application for use that will manipulate this data in the database the strong suggestion is:

1) Move to another programming language - (in which for example, you do not have to worry about the bytes size of the query buffer for MySQL, as I mentioned in the question). I suggest studying a very high level dynamic language like Python, Javascript or Ruby (PHP already has some idiosyncrasies that can introduce addictions in this learning stage - I would not recommend - in particular you will be very tempted to mix code with presentation)

2) Even if you use such an application, using the terminal from a certain point will complicate the application for both you and the developer (as you can see in the link above, using Python does not magically reduce the complexity of display a table in the terminal correctly to zero). So it's cool to get a web framework and develop the web application - it's much simpler to put the query output in a bnaco where each field is inside a <td>...</td> tag than to manually worry about the width of the table (in addition, with the output in html, you can separately with CSS, limit the width of the columns and configure to truncate the data, or display scrollbars in your cells).

3) If you are going to stay in C to learn it, I would still recommend changing the focus of your application to generate the outputs in ".csv" files, which you can open in a program. spreadsheet - and you can focus on the control and operation of the database itself in your app. (notice that in the languages I mentioned above, interacting with the database is also proportionally easier).

(As for your current code I do not even know how you got the partial result with the column names - your image shows 5 columns, but you only make a call to mysql_fetch_field which is what returns information, name, of the columns, and does not do this in any loop - since the function only brings information from one column at a time: link

That is, if this is the code that actually generates the result you show, the expression campos[contador].name is only working by chance, due to an undocumented feature of the mysql function)

    
18.06.2018 / 16:42