Good morning, I'm very new in the programming environment and I'm doing some test programs.
I'm using c ++ in codeblocks and mysql connector. This is a segment of the code. What I want to do is send the value of the variable "t" that increases each cycle. But I get segmentation fault before I get to the last if (! Qstate).
I hope you can help me find my mistake or any suggestion to avoid it. Greetings.
#include <iostream>
#include <unistd.h>
#include <mysql++/mysql++.h>
#include <wiringPi.h>
#include <fstream>
#include <string.h>
#include <sstream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
MYSQL* conn;
MYSQL_ROW row;
MYSQL_RES* res;
int qstate; //stores query status after execution
conn = mysql_init(0);
if(conn) // if SUCCEEDED
{
cout<<"connection object ok"<<endl;
}
else
{
cout << "conn object problem!" <<mysql_error(conn) << endl;
conn = mysql_real_connect(conn,"localhost","root","1234","prueba2",0,NULL,0);
}
if(conn) // if SUCCEEDED
{
cout<<"connection to database done!!"<<conn<<endl;
//before select, it will insert first. So new record will be displayed
wiringPiSetup();
pinMode(0,OUTPUT);
pinMode(24,INPUT);
int a = 0;
for (a = 0; a = 1; a+ digitalRead(24))
{
float t;
if(digitalRead(24) == HIGH)
{
int i = 0;
for (i = 0;i<3;i++)
{
digitalWrite(0,HIGH);
delay(900);
cout <<"Enciende"<<endl;
digitalWrite(0,LOW);
delay(900);
cout <<"Apaga"<<endl;
}
t=t+a;
cout<<t<<endl;
}
stringstream ss;
ss<<t<<endl;
string t2 = ss.str();
string query="insert into tabla2 (id) values('"+ t2+"')";
//const char converst string object to const char as it is requires in mysql_query(conn,q)
const char * q = query.c_str();
cout<<"query is: "<<q<<endl;
qstate = mysql_query(conn,q);
if(!qstate) //if insert succeeded
cout<<"record inserted successfully..."<<endl;
else
cout<<"query problem: "<<mysql_error(conn)<<endl;
// dasdsa
//now lets run select query on db table
qstate = mysql_query(conn,"select * from tabla2");
if(!qstate) //means nonzero
{
//get records from conn object to res* pointer
res = mysql_store_result(conn);
//now read an display record one @ time
while(row=mysql_fetch_row(res))
{
cout<<"id: "<<row[0]<<endl;
}
}
else
{
cout << "query execution problem!" <<mysql_error(conn) << endl;
}
//its done
}
}
else
{
cout << "conn object problem!" <<mysql_error(conn) << endl;
}
return 0;
}