I need an advice from community. I need to store somewhere data from mysql so later I could compare data. I tried to put everything to struct, but I realized that struct was gone after loop, and that i cannot create that struct name would be variable. Like this:
struct Columns (variable);
So basically I need to store columns information like field, type, key etc.. I don't know how much there will be tables.
My struct:
struct Columns {
char field[1000];
char type[50];
char null[10];
char key[20];
char defaul[50];
char extra[50];
};
Code part:
if (mysql_query(conn, "Show tables;")){
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_store_result(conn);
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL){
printf("%s\n", row[0]);
sprintf(str, "Show columns from %s;", row[0]); //row[0]-is table names
sprintf(str1, "lentele_%s", row[0]);
printf("%s\n", str1);
struct Columns str1;
if (mysql_query(conn, str)){
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res2 = mysql_use_result(conn);
while ((row2 = mysql_fetch_row(res2)) != NULL){
strcpy(str1.field, row2[0]);
printf("Belekas Column field %s\n", str1.field);
}
There are 6 columns on each table: field || type || null || key || default || extra
As I said, i will need that data for later comparison.
Related
I have written a c program that I hoped would read data from a text file and put it in a database.
The problem is that the code doesn't execute all iterations of a while loop in the main function as I hoped it would
#Explanation of the algorithm#
The program opens the file that contains the records and reads the whole file into a buffer. Then it chops the string
into records seperated by \n. It then gets each record and composes an sql insert statement then writes the record to the database
Here is the code:
#include <stdio.h>
#include <string.h>
#include <mysql.h>
#define MAX_LEN 1000
/*
#Explanation of the algorithm#
The program opens the file that contains the recored and reads the whole file into a buffer. Then it chops the string
into records. it then gets each record and composes an sql insert statement then writes the record to the database
*/
// function to change the date format to the correct database format
const char* date_formater(char date[],char search_for,char new)
{
int i;
for(i = 0; i <= strlen(date); i++)
{
if(date[i] == search_for)
{
date[i] = new;
}
}
return date;
}
// send data to the database
void send_data_to_database(char str[],MYSQL *con)
{
/*Get data to send to the database*/
char data[8][100];
char delimeter[] = "\t";
char *token = strtok(str,delimeter);
int i = 0;
while(token != NULL)
{
strcpy(data[i],token);
token = strtok(NULL,delimeter);
i++;
}
char o_id[] = "0";
strcpy(data[7],o_id);
// generate sql insert statement
char closingbrac[] = ")";
char single_quote[] = "\'";
char comma[] = ",";
char sql[200] = "INSERT INTO patient VALUES(";
for(int j = 0;j<=7;j++)
{
switch(j)
{
case 0:
strcat(sql,data[j]);
strcat(sql,comma);
break;
case 2:
strcat(sql,single_quote);
const char* real_date = date_formater(data[j],'/','-'); // change date to databse required format
strcat(sql,real_date);
strcat(sql,single_quote);
strcat(sql,comma);
break;
case 7:
strcat(sql,data[j]);
strcat(sql,closingbrac);
printf("%s\n",data[j] );
break;
default:
strcat(sql,single_quote);
strcat(sql,data[j]);
strcat(sql,single_quote);
strcat(sql,comma);
}
}
printf("%s\n",sql);
/*Send SQL query*/
if(mysql_query(con,sql))
{
fprintf(stderr, "%s\n",mysql_error(con));
exit(1);
}
}
/*control function*/
int main()
{
MYSQL *conn;
char *server = "localhost";
char *user = "root";
char *password = "MasterY";
char *database = "covid";
conn = mysql_init(NULL);
/*Connect to database*/
if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0))
{
fprintf(stderr, "%s\n",mysql_error(conn));
exit(1);
}
// open the file containing the patient records
FILE *fptr;
fptr = fopen("/home/elijah/Desktop/plan.txt","r");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
//open the file containing records for reading
char string[MAX_LEN + 1];
// get all the file contents and store them in a string
fscanf(fptr,"%[^$]",string);
printf("Text file contents:\n%s\n",string);
//puts(string);
printf("String: \n%s\n",string);
char delim[] = "\n";
char *ptr = strtok(string,delim);
while(ptr != NULL)
{
// function call to send data to the database
send_data_to_database(ptr,conn);
ptr = strtok(NULL,delim);
}
/*close connection*/
mysql_close(conn);
//closing the file and clearing it
fclose(fptr);
FILE *file;
file = fopen("/home/elijah/Desktop/plan.txt","w");
fclose(file);
printf("Execution\n");
return 0;
}
The compiler executes the main function up to the while loop. And funnily it only executes one iteration and stops after the first iteration.
Yet I hoped it would continue and finish all the different lines in the text file
It executes the send_data_to_database(ptr,conn); completely.
Here is the text file. Every line is a record that has to be inserted into a database
6 Okello Ivan 2020/10/11 False Positive Assymptomatic M John
7 Leku Davis 2020/02/03 Positive Assymptomatic M Malik Berry
8 Okello Ivan 2020/10/11 False Positive Assymptomatic M John
9 Leku Davis 2020/02/03 Positive Assymptomatic M Malik Berr
Here is a copy of the output:
It only inputs one record into the db. Yet I hoped that it would insert all. I don't know what the problem is but I know something isn't right. That's why I am here.
elijah#elijah-HP-255-G6-Notebook-PC:~/Desktop$ ./mysql
Text file contents:
6 Okello Ivan 2020/10/11 False Positive Assymptomatic M John
7 Leku Davis 2020/02/03 Positive Assymptomatic M Malik Berry
8 Okello Ivan 2020/10/11 False Positive Assymptomatic M John
9 Leku Davis 2020/02/03 Positive Assymptomatic M Malik Berry
String:
6 Okello Ivan 2020/10/11 False Positive Assymptomatic M John
7 Leku Davis 2020/02/03 Positive Assymptomatic M Malik Berry
8 Okello Ivan 2020/10/11 False Positive Assymptomatic M John
9 Leku Davis 2020/02/03 Positive Assymptomatic M Malik Berry
0
INSERT INTO patient VALUES(6,'Okello Ivan ','2020-10-11 ','False Positive ','Assymptomatic ','M ','John',0)
Execution
This is the database table SQL CREATE statement for a MYSQL Database.
CREATE TABLE `patient` (
`idpatient` int(11) NOT NULL AUTO_INCREMENT,
`fullname` varchar(255) NOT NULL,
`date-of-id` date DEFAULT NULL,
`covid-status` varchar(45) DEFAULT NULL,
`nature` varchar(45) DEFAULT NULL,
`gender` varchar(30) DEFAULT NULL,
`officer_name` varchar(45) DEFAULT NULL,
`o-id` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idpatient`,`fullname`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
I compile the source code using this command:
gcc -o mysql -I/usr/include/mysql addtodatabase.c -L/usr/lib/x86_64-linux-gnu -lmysqlclient -lpthread -lz -lm -lrt -latomic -lssl -lcrypto -ldl
Because I used #include <mysql.h>
Someone please help me.
#UPDATE
I found out that I could use a csv file to push that data to the database since it's already in tabular format. But I am finding trouble using the LOAD DATA statement.
Here is the updated code
#include <stdio.h>
#include <string.h>
#include <mysql.h>
#define MAX_LEN 1000
/*
#Explanation of the algorithm#
The program opens the file that contains the recored and reads the whole file into a buffer. Then it chops the string
into records. it then gets each record and composes an sql insert statement then writes the record to the database
*/
// function to change the date format to the correct database format
const char* formater(char date[],char search_for,char new)
{
int i;
for(i = 0; i <= strlen(date); i++)
{
if(date[i] == search_for)
{
date[i] = new;
}
}
return date;
}
// send data to the database
void send_data_to_database(MYSQL *con)
{
// SQL QUERY
char sql[] = "LOAD DATA LOCAL INFILE '/home/elijah/Desktop/cron_job/patients.csv' INTO TABLE patient COLUMNS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES (`idpatient`,`fullname`,`date-of-id`,`covid-status`,`nature`,`gender`,`officer_name`,`o-id`)";
/*Send SQL query*/
if(mysql_query(con,sql))
{
fprintf(stderr, "%s\n",mysql_error(con));
exit(1);
}
else
{
printf("Data Sent\n");
}
}
/*control function*/
int main()
{
MYSQL *conn;
char *server = "localhost";
char *user = "root";
char *password = "MasterY";
char *database = "covid";
conn = mysql_init(NULL);
/*Connect to database*/
if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0))
{
fprintf(stderr, "%s\n",mysql_error(conn));
exit(1);
}
// open the file containing the patient records
FILE *fptr;
fptr = fopen("/home/elijah/Desktop/cron_job/patients.txt","r");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
//open the file containing records for reading
char string[MAX_LEN + 1];
// get all the file contents and store them in a string
fscanf(fptr,"%[^$]",string);
printf("Text file contents:\n%s\n",string);
//puts(string);
printf("String: \n%s\n",string);
// put the data into csv file format and write it
const char *formated_csv_string = formater(string,'\t',',');
char csv_string[] = "idpatient,fullname,date-of-id,covid-status,nature,gender,officer_name,o-id\n";
strcat(csv_string,formated_csv_string);
printf("%s\n",csv_string);
FILE *csv_file;
csv_file = fopen("/home/elijah/Desktop/cron_job/patients.csv","w");
if(csv_file == NULL)
{
printf("Crap\n");
}
else
{
printf("Yayyyyy\n");
fprintf(csv_file, "%s",csv_string);
}
send_data_to_database(conn);
/*close connection*/
mysql_close(conn);
//closing the file and clearing it
fclose(fptr);
// FILE *file;
// file = fopen("/home/elijah/Desktop/cron_job/patients.txt","w");
// fclose(file);
printf("Execution\n");
return 0;
}
The LOAD DATA SQL statement does not work. What could be the problem.
Here is the output
elijah#elijah-HP-255-G6-Notebook-PC:~/Desktop$ ./mysql
Text file contents:
1 Okello Ivan 2020/08/13 False Positive Assymptomatic M Mary 0
String:
1 Okello Ivan 2020/08/13 False Positive Assymptomatic M Mary 0
idpatient,fullname,date-of-id,covid-status,nature,gender,officer_name,o-id
1,Okello Ivan ,2020/08/13 ,False Positive ,Assymptomatic ,M ,Mary,0
Yayyyyy
Data Sent
Execution
If we know there are 3 results. Can we replace the while loop below:
res = mysql_use_result(co);
row = mysql_fetch_row(res);
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
With the following code?:
row = mysql_fetch_row(res)
printf("%s \n", row[0]);
row = mysql_fetch_row(res)
printf("%s \n", row[0]);
row = mysql_fetch_row(res)
printf("%s \n", row[0]);
How does it know which result to fetch?
It keeps track of an index in the result data structure. When you call fetch_row, it will return the next row, then increase the index by 1. Once there are no more rows that can be returned, it will return null (which is what terminates the while loop in the first case).
I'm new to mysql programming on c. I need to check if a certain user exists in a table. How can I do this using the C API?
Here's what I've got, but it isn't working:
if (mysql_query(con, "SELECT * FROM Users WHERE UserName='user3'"))
{
finish_with_error(con);
}
MYSQL_RES *result = mysql_store_result(con);
if (result == NULL)
{
finish_with_error(con);
}
int count = mysql_field_count(con);
printf("%d\n", count );
For anyone interested, this is something I wrote using the comments, and finally ended up using.
if (mysql_query(con, "SELECT field FROM table WHERE userName='user1'"))
{
finish_with_error(con);
}
MYSQL_RES *result = mysql_store_result(con);
if (result == NULL)
{
finish_with_error(con);
}
MYSQL_ROW row;
MYSQL_FIELD *field;
if (row = mysql_fetch_row(result))
{
printf("%s\n", row[0]);
db_pwd = row[0];
}
Im trying to call my str date variable in this function:
int main(int argc, char **argv)
{
int status = 0;
char query[300], data[15], hora[10];
strDataHora(data, hora);
printf("Date: %s\n", data);
MYSQL *con = mysql_init(NULL);
if (con == NULL)
{
fprintf(stderr, "mysql_init() failed\n");
exit(1);
}
if (mysql_real_connect(con, "localhost", "root", "ufmg3duc",
"stream_net", 0, NULL, CLIENT_MULTI_STATEMENTS) == NULL)
{
finish_with_error(con);
}
if (mysql_query(con, "SELECT Id FROM audiencia WHERE data LIKE ('%s') AND (hora LIKE ('%:00:%') OR hora LIKE ('%:30:%')) AND hora > '03:01'",data))
{
finish_with_error(con);
}
But I dont know how to call 'date' in mysql_query:
if (mysql_query(con, "SELECT Id FROM audiencia WHERE data LIKE ('%s') AND (hora LIKE ('%:00:%') OR hora LIKE ('%:30:%')) AND hora > '03:01'",data))
How can i select Id when my actual date is a str variable type?
You have to store this query in a variable (eg. with sprintf or snprintf) and escape all those %using %%
char query[300];
...
sprintf(query, "SELECT Id FROM audiencia WHERE data LIKE ('%s') ...", data);
mysql_query(con, query);
I created this table (results) in my sql database (test)
CREATE DATABASE `test`;
USE `test`;
CREATE TABLE `results` (
`number` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`id_machine` int(10) unsigned NOT NULL,
`value` float NOT NULL,
`datetime` datetime NOT NULL,
PRIMARY KEY (`number`),
UNIQUE KEY `indice_UNIQUE` (`number`)
) ENGINE=InnoDB AUTO_INCREMENT=100;
My external device gives me these results:
+DATA: 43 BYTES FROM 0000:0000 (045)
Machine_8: (T=22.22, HR=42.56, Dw=8.95, VCC=3.64V)
and with the usage of strtok I get some values of these results to save them in the database:
Results: 8, 22.22, 42.56, 8.95, 3.64
I would like to save my data in my table in this way:
101, 8, 22.22, 2013-06-05 14:03:00
102, 8, 42.56, 2013-06-05 14:03:00
103, 8, 8.95, 2013-06-05 14:03:00
104, 8, 3.64, 2013-06-05 14:03:00
This is my code in my function until now
int learn_port2(int fd)
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_RES *res1;
MYSQL_ROW row;
char *server = "127.0.0.1";
char *user = "root";
char *password = "***"; // got tot keep my data secret
char *database = "test";
conn = mysql_init(NULL);
if(!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0))
{
fprintf(stderr, "%s\n", mysql_error(conn));
return -1;
//finish_with_error(conn);
}
int n, i;
char buff[300];
memset(buff, 0, sizeof(buff));
for (int x = 0; x<1; x++)
//for (;;)
{
char id_machine[35] = "";
char temp[35] = "";
char hum[35] = "";
char dw[35] = "";
char vol[45] = "";
char* ptr;
int i,nodo,nodo1;
float temp, hum, dw, vcc;
n=read(fd,buff,sizeof(buff));
sleep(1);
printf("%s", buff);
printf("\n");
if (buff[37] == 'N' || buff[38] == 'N' || buff[39] == 'N' || buff[40] == 'N' )
{
ptr = strtok(buff, "Machine_,=T:HR:DW:Vcc()");
i = 0;
while (ptr != NULL)
{
if (i == 9)
strcat(id_machine, ptr); // copies Nodo
if (i == 10)
strcat(temp, ptr); // copies T
if (i == 11)
strcat(hum, ptr); // copies HR
if (i == 13)
strcat(dw, ptr); // copies DW
if (i == 15)
strcat(vol, ptr); // copies Vcc
ptr = strtok(NULL, "Machine_,=T:HR:DW:Vcc()");
i++;
}
printf("Results: %s, %s, %s, %s, %s\n", id_machine, temp, hum, dw, vol);
}
char query[]="INSERT INTO results(`id_machine`,`value`,`valor`) VALUES(id_machine,'14',value)";
if(mysql_query(conn, query))
{
fprintf(stderr, "%s\n", mysql_error(conn));
return -1;
}
res = mysql_use_result(conn);
}
}
How can I modify the char query[] to have the results which I want? Or if there are some examples like this.
To make a parameterized query you could use something like the following...
The example uses vsnprintf() to take a printf like format string and a variable number of arguments after it to print the query into a temporary buffer and then pass the buffer to the MYSQL query. In this way you can get a paramaterized query...
vsnprintf() accepts a variable parameter list, va_list and also is buffer-overflow safe.
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#define BUFSTRLEN 255
/* Returns -1 if the internal buffer was not large enough to hold the formatted
* string, or a format error occurred. If neither condition occurred then the
* result of the MYSQL query is returned... */
int DoMysqlQuery(MYSQL *conn, char const *printfstring, ...)
{
int len;
va_list args;
char buffer[BUFSTRLEN + 1];
memset(buffer, '\0', sizeof(buffer));
va_start(args, printfstring);
len = vsnprintf(buffer, BUFSTRLEN, printfstring, args);
va_end(args);
/* Did the buffer print work ? */
if( len < 0 || len >= BUFSTRLEN + 1 )
return -1;
return mysql_query(conn, buffer);
}
int main(int argc, char const *argv[])
{
int result;
MYSQL mysqlConn = ...;
/* Example stuff to send to the function.... */
char *id_machine= "8";
char *value= "1234";
char *valor= "1";
/* Send the query */
result = DoMysqlQuery(
&mysqlConn,
"INSERT INTO results(`id_machine`,`value`,`valor`) VALUES(%s,'%s',%s);",
id_machine, value, valor);
if( result )
{
/* handle error etc... *.
}
}
In this example, the query string that will be sent to mysql_query() is:
INSERT INTO results(id_machine,value,valor) VALUES(8,'1234',1);
Hope this helps :)