Not working Code:
#include "stdafx.h"
#include <stdio.h>
#include "sqlite3.h"
#include <Windows.h>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
std::vector<string> emailsfound;
static int callback(void *data, int argc, char **argv, char **azColName)
{
int i;
string thefile;
for(i=0; i<argc; i++)
{
thefile = string(argv[i]);
size_t found = thefile.find(":");
if(found != std::string::npos)
{
thefile.erase(thefile.begin(), thefile.begin()+1);
emailsfound.push_back(thefile);
//here's the problem
cout << emailsfound[i] << endl; //here it only couts emailsfound[0] over and over until the loop's work is done.
}
else
{
}
}
return 0;
}
int main(int argc, char* argv[])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called"; //I am not printing this
/* Open database */
rc = sqlite3_open("C:\\Users\\main.db", &db);
if( rc )
{
return 0;
}
else
{
}
/* Create SQL statement */
sql = "SELECT emails from People";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if( rc != SQLITE_OK )
{
sqlite3_free(zErrMsg);
return 0;
}
else
{
}
sqlite3_close(db);
system("PAUSE");
return 0;
}
Working Code:
#include "stdafx.h"
#include <stdio.h>
#include "sqlite3.h"
#include <Windows.h>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
std::vector<string> emailsfound;
static int callback(void *data, int argc, char **argv, char **azColName)
{
int i;
string thefile;
for(i=0; i<argc; i++)
{
thefile = string(argv[i]);
size_t found = thefile.find(":");
if(found != std::string::npos)
{
thefile.erase(thefile.begin(), thefile.begin()+1);
emailsfound.push_back(thefile);
//Doing this makes it works great.
printthevector();
}
else
{
}
}
return 0;
}
void printthevector()
{
int sizeofthevector;
int i = 0;
sizeofthevector = emailsfound.size();
while (i < sizeofthevector)
{
cout << emailsfound[i].c_str() << endl; //print everything / it works great
}
}
int main(int argc, char* argv[])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called"; //I am not printing this
/* Open database */
rc = sqlite3_open("C:\\Users\\main.db", &db);
if( rc )
{
return 0;
}
else
{
}
/* Create SQL statement */
sql = "SELECT emails from People";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if( rc != SQLITE_OK )
{
sqlite3_free(zErrMsg);
return 0;
}
else
{
}
sqlite3_close(db);
system("PAUSE");
return 0;
}
As you can see, in the first code it only counts emailsfound[0] over and over for some reason so I had to create a proper void to cout all the emails found properly.
Please explain this to me, I know I fixed it but I am not sure why the first code was not working.
Related
I've been making program that need to continuously insert data to a database. I'm new to C++.
I'm using xampp for my database. I want to make insert loop inside one of my function.
my code looks like this
#include "stdio.h"
#include "fstream"
#include "iostream"
#include "mysql.h"
#include "sstream"
void loop();
void print();
int i;
const char* hostname = "localhost";
const char* username = "root";
const char* password = "";
const char* database = "testinsertdb";
unsigned int port = 3306;
const char* unixsocket = NULL;
unsigned long clientflag = 0;
insertion(){
MYSQL* conn;
conn = mysql_init(0);
conn = mysql_real_connect(conn, hostname, username, password, database, port, unixsocket, clientflag);
int qstate=0;
using namespace std;
stringstream ss;
ss << " INSERT INTO test (number) values ('" <<i<<"')";
string query = ss.str ();
const char * q = query.c_str();
qstate = mysql_query(conn, q);
if (qstate == 0)
{
cout <<" Record inserted successfully ..."<<endl;
}
else
{
cout <<" Error, data not inserted..."<<endl;
}
}
int main()
{
print();
return 0;
}
void print()
{
for (int j = 0; j < 1000000; j++) {
loop();
}
}
void loop()
{
i=1;
insertion();
}
When I run the program, I managed to insert some data to the database, but after several seconds the program stopped with code -10737741819 (0xC0000005). On my build log Process the terminated with status -1073741510
How can i solve this?
Preferablly try this one.
Your code is trying to connect database as many times as the loop proceeds.
There is the description of that error from this link
#include "stdio.h"
#include "fstream"
#include "iostream"
#include "mysql.h"
#include "sstream"
void loop();
void print();
MYSQL* conn;
const char* hostname = "localhost";
const char* username = "root";
const char* password = "";
const char* database = "testinsertdb";
unsigned int port = 3306;
const char* unixsocket = NULL;
unsigned long clientflag = 0;
void insertion() {
int qstate=0, i;
using namespace std;
stringstream ss;
ss << " INSERT INTO test (number) values ('" <<i<<"')";
string query = ss.str ();
const char * q = query.c_str();
qstate = mysql_query(conn, q);
if (qstate == 0)
{
cout <<" Record inserted successfully ..."<<endl;
}
else
{
cout <<" Error, data not inserted..."<<endl;
}
}
int main()
{
print();
return 0;
}
void print()
{
conn = mysql_init(0);
conn = mysql_real_connect(conn, hostname, username, password, database, port, unixsocket, clientflag);
for (int j = 0; j < 1000000; j++) {
loop();
mysql_close(conn);
}
void loop()
{
i=1;
insertion();
}
I wrote a server using cpp to connect mysql with libmysqlclient.a, codes are like this:
#ifndef __IVC_MYSQLAPI_H__
#define __IVC_MYSQLAPI_H__
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <mysql.h>
#include <string.h>
#include <vector>
using namespace std;
class ConnMysql {
public:
ConnMysql();
~ConnMysql();
int connInit(const char* host,int port,const char* user,const char* password,const char* database);
int executeSql(const char* sql, std::vector<std::string> &v);
void close();
private:
MYSQL *sock;
MYSQL *my_sql;
};
ConnMysql::ConnMysql(){
}
ConnMysql::~ConnMysql(){
}
int ConnMysql::connInit(const char* host,int port,const char* user,const char* password,const char* database){
my_sql = mysql_init(NULL);
if (my_sql == NULL) {
fprintf(stderr, "Init failed\n");
return -1;
}
sock = mysql_real_connect(my_sql, host,
user, password, database, port, NULL, CLIENT_MULTI_STATEMENTS);
if (sock < 0) {
return -1;
}
}
int ConnMysql::executeSql(const char* sql, std::vector<std::string> &v) {
mysql_query(sock, sql);
MYSQL_RES *res_ptr;
res_ptr = mysql_store_result(sock);
if(res_ptr == nullptr) {
printf("Get data from mysql failed\n");
return -1;
}
MYSQL_ROW sqlrow;
int j = mysql_num_fields(res_ptr);
while((sqlrow = mysql_fetch_row(res_ptr))) {
v.push_back(std::string(sqlrow[0]));
}
return 0;
}
void ConnMysql::close() {
mysql_close(sock);
sock=NULL;
my_sql = NULL;
}
#endif //__IVC_MYSQLAPI_H__
The method called like this:
ConnMysql connsql = ConnMysql{};
fprintf(stderr, "begin to init\n");
if (connsql.connInit(ip, port, username, pwd, database) < 0) {
fprintf(stderr, "mysql init return failed\n");
return -1;
}
std::string sql = "select env_code from env_codes where env_type = 1";
connsql.executeSql(sql.c_str(), v);
for (int len=0; len < v.size(); len++) {
fprintf(stderr, "get: %s\n", v[len].c_str());
}
connsql.close();
I will get error suchInit failed occasionally, not always. My questions are
Is there any wrong with my codes? Forget to release something?
How can get the reason why mysql init failed?
I changed mysql_real_connect like this
if(mysql_real_connect(my_sql, host,
user, password, database, port, NULL, CLIENT_MULTI_STATEMENTS) == NULL)
{
return -1;
}
and delete MYSQL *sock parameter, and changed sock to my_sql, such as mysql_query(sock, sql) to mysql_query(my_sql, sql). It seems workable.
I'm trying to work with a database in C++. I made a program that opens the database and then creates the tables in procedural programming.
When trying to make it in OOP, sqlite3_exec() != SQLITE_OK
I am new at this, so be gentle.
Here is main.cpp:
#include <iostream>
#include "sqlite3.h"
#include "Table.h"
using namespace std;
int openDatabase(sqlite3 *db);
int main() {
sqlite3 *db;
string columnValues, rowValues; // these are for query
Table Personal;
Personal.SettableName("PERSONAL");
columnValues = "NUME TEXT, ID TEXT"; // this is just an example
openDatabase(db);
Personal.createTable(db, columnValues);
sqlite3_close(db);
return 0;
}
Table.cpp
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "Table.h"
#include "sqlite3.h"
using namespace std;
static int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char*)data);
for(i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
void executeSqlStatement(sqlite3 *db,const char* sql) {
int rc = 0 ;
char *zErrMsg = 0;
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); // Here it doesn't work, rc=21;
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else {
fprintf(stdout, "Operation done successfully\n");
}
}
void Table::createTable(sqlite3 *db, string columnDetails) {
this->sqlCommand = "CREATE TABLE ";
this->sqlCommand += (this->tableName + " (" + columnDetails + ");");
executeSqlStatement(db, this->sqlCommand.c_str());
printf(sqlCommand.c_str());
}
And Table.h
#include "sqlite3.h"
using namespace std;
void executeSqlStatement(sqlite3 *db);
static int callback(void *data, int argc, char **argv, char **azColName);
class Table
{
public:
void SettableName(string val){tableName = val;}
void createTable(sqlite3 *db, string columnDetails);
string tableName;
string sqlCommand;
};
Including the sqlite3.h file in all three files is not necessary, as Table.h was included by both the cpp files, so you only needed to have it in that file.
The sqlite3.h file is also a system file, so using include <sqlite3.h> instead of include "sqlite3.h" makes it clearer where the file is coming from.
I would recommend compiling with the -Wall and -Wextra flags - at first they appear to make loads of complaints but it is worth paying attention to the problems reported and working out how to fix them.
Table.h
#include <sqlite3.h>
using namespace std;
void executeSqlStatement(sqlite3 *db);
int callback(void *data, int argc, char **argv, char **azColName);
class Table
{
public:
void SettableName(string val){tableName = val;}
void createTable(sqlite3 *db, string columnDetails);
string tableName;
string sqlCommand;
};
Table.cpp
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "Table.h"
using namespace std;
int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char*)data);
for(i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
void executeSqlStatement(sqlite3 *db,const char* sql) {
int rc = 0 ;
char *zErrMsg = 0;
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); // Here it doesn't work, rc=21;
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else {
fprintf(stdout, "Operation done successfully\n");
}
}
void Table::createTable(sqlite3 *db, string columnDetails) {
this->sqlCommand = "CREATE TABLE ";
this->sqlCommand += (this->tableName + " (" + columnDetails + ");");
executeSqlStatement(db, this->sqlCommand.c_str());
printf(sqlCommand.c_str());
}
main.cpp
#include <iostream>
#include "Table.h"
using namespace std;
int main() {
sqlite3 *db;
sqlite3_open_v2("test.db", &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
string columnValues, rowValues; // these are for query
Table Personal;
Personal.SettableName("PERSONAL");
columnValues = "NUME TEXT, ID TEXT"; // this is just an example
Personal.createTable(db, columnValues);
sqlite3_close(db);
return 0;
}
On my github I have a working version of your code, with a (borrowed) makefile to pull the files together so I just have to type make debug to compile the code.
make debug && bin/debug/hello
will build the file, and if the compilation was successful run the executable.
Hello i compliled my c++ program and if i start the .exe i got a error
Image from the error
This is my source(main.cpp):
#include <iostream>
#include <string>
#include <Windows.h>
#include <dos.h>
#include <stdio.h>
#include <fstream>
#include <ctime>
// using
using namespace std;
bool fexists(const char *filename);
int main() {
try {
HANDLE h;
string cClipboard = "";
CreateDirectory("C:\\Program Files\\Clipboard Logger", NULL);
if (!fexists("C:\\Program Files\\Clipboard Logger\\log.txt")) {
FILE *fp;
fp = fopen("C:\\Program Files\\Clipboard Logger\\log.txt", "w");
fclose(fp);
}
while (true) {
if (!OpenClipboard(0)) {
Sleep(2000);
continue;
}
h = GetClipboardData(CF_TEXT);
CloseClipboard();
if ((char *)h == cClipboard) {
Sleep(2000);
continue;
}
cClipboard = (char *)h;
time_t t = time(0);
struct tm * now = localtime(&t);
FILE *fp;
fp = fopen("C:\\Program Files\\Clipboard Logger\\log.txt", "a");
int day = now->tm_mday;
int month = now->tm_mon + 1;
int year = now->tm_year + 1900;
int sec = now->tm_sec;
int min = now->tm_min;
int hour = now->tm_hour;
char logLine[sizeof((char *)h) + 64];
sprintf(logLine, "%d.%d.%d %d.%d.%d %s\n", hour, min, sec, day, month, year, (char *)h);
fprintf(fp, (char *)logLine);
fclose(fp);
cout << (char *)logLine << endl;
Sleep(2000);
}
getchar();
return 0;
} catch (...) {
}
}
bool fexists(const char *filename) {
ifstream ifile(filename);
if (ifile)
return true;
return false;
}
iam new in c++ and i dont know how to fix it, because if i debug the program all works fine but with the exe it doesnt work.
using sqlite3 C++ bindings with GCC(MINGW) 4.6.2
the following code does not work i.e the callback function does not print anything to the screen.
Any suggestions?
#include <iostream>
#include "sqlite3.h"
using namespace std;
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
for (int i=0; i<argc; i++)
{
cout << azColName[i] << "=" << argv[i] << endl;
cout << "\n" << endl;
}
return 0;
}
class db
{
public:
sqlite3* mydb;
char database;
char* mysql;
char* zErrMsg;
db()
{
zErrMsg = 0;
}
void open(string mydatabase)
{
sqlite3_open(mydatabase.c_str(), &mydb);
}
void exec(char* mysql)
{
int rc = sqlite3_exec(mydb, mysql, callback, 0, &zErrMsg);
}
void close()
{
sqlite3_close(mydb);
}
};
int main()
{
db* mystorage;
string s_var = "test.db";
char* sql = "SELECT * FROM COMPANY;";
mystorage -> open(s_var);
mystorage -> exec(sql);
mystorage -> close();
return 0;
}