I want to read data from txt file and insert it into SQlite database table with C++. I prepared a code but it doesn't work.
Example line from my txt file is follows;
',1417392060.000000','1.245430','1.2456','1.24469','1.245000'
And code;
sqlite3 *db;
char *zErrMsgt = 0;
int rct;
int rch;
int rchi;
rct = sqlite3_open("final.db", &db);
if( rct ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
}else{
fprintf(stdout, "Opened database successfully\n");
}
string resline;
ifstream res("Res.txt");
while(getline(res,resline)){
string sqlli = "INSERT into FOREXNEW(DATE,OPEN,HIGH,LOW,CLOSE) VALUES ("getline(res,resline)");";
rchi = sqlite3_exec(db, sqlli.c_str(), callback, 0, &zErrMsgt);
if( rchi != SQLITE_OK ){
cout << "SQL error:" << zErrMsgt;
sqlite3_free(zErrMsgt);
}}
sqlite3_close(db);
Any alternate suggestions and solutions will be appreciated as well:) Thank you.
Getline doesn't return a string; it copies it to the variable passed in the second parameter. Change the erroneous line:
string sqlli = "INSERT into FOREXNEW(DATE,OPEN,HIGH,LOW,CLOSE) VALUES ("getline(res,resline)");";
to:
string sqlli = "INSERT into FOREXNEW(DATE,OPEN,HIGH,LOW,CLOSE) VALUES ("+resline+");";
And check if it works.
Related
I know their is another question with this exact title but it doesn't solve my problem, so here goes.
I am following a tutorial on using SQLite with c++, but when I run my program to create the database table, I get an error;
static int create_database(const char *s);
static int create_table(const char *s);
int main(){
const char *file = "Mafia.sqlite";
sqlite3 *db;
create_database(file);
create_table(file);
}
static int create_database(const char* s){
sqlite3 *db = NULL;
int query = 0;
query = sqlite3_open_v2(s, &db, SQLITE_OPEN_CREATE, NULL);
cout << "Database created successfully!\n";
sqlite3_close(db);
return 0;
}
static int create_table(const char* s){
sqlite3 *db;
string sql = "CREATE TABLE IF NOT EXISTS USERS("
"ID INTEGER PRIMARY KEY AUTOINCREMENT,"
"USERNAME TEXT NOT NULL,"
"PASSWORD TEXT NOT NULL);";
try{
int query = 0;
query = sqlite3_open_v2(s, &db, SQLITE_OPEN_READWRITE, NULL);
char *error_message;
query = sqlite3_exec(db, sql.c_str(), NULL, 0, &error_message);
if(query != SQLITE_OK){
cerr << "Error occurred creating table!\n";
sqlite3_errmsg(db);
sqlite3_free(error_message);
}else
cout << "Table created successfully\n";
sqlite3_close(db);
}
catch(const exception &e){
cerr << e.what() << '\n';
}
}
My terminal returns the following:
Database created successfully!
Error occurred creating table!
test(13698,0x109148dc0) malloc: Non-aligned pointer 0x102bd9641 being freed
test(13698,0x109148dc0) malloc: *** set a breakpoint in malloc_error_break to debug
Edit
I corrected the sql error and I still have the same problem
Thanks.
There are couple of things,
First you need to initialize error_message to nullptr. Otherwise sqlite3_free will cause a crash since error_message is having some garbage value.
Secondly, according to the SQLITE documentation, you need to use atleast one of the three options while opening an SQLITE connection,
SQLITE_OPEN_READONLY
SQLITE_OPEN_READWRITE
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
You are not supposed to use SQLITE_OPEN_CREATE as a standalone option.
If you change these two, it should work fine.
I'm working in Visual Studio Community 2017, and what I'm trying to do is open and read the information of a database in C++.
#include <stdio.h>
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
#include "C:\Users\santiago.corso\Desktop\sqlite-amalgamation-3240000 (1)\sqlite-amalgamation-3240000\sqlite3.h"
bool find_employee(int _id)
{
bool found = false;
sqlite3* db;
sqlite3_stmt* stmt;
stringstream ss;
// create sql statement string
// if _id is not 0, search for id, otherwise print all IDs
if (_id) { ss << "select * from employees where id = " << _id << ";"; }
else { ss << "select * from employees;"; }
string sql(ss.str());
//the resulting sql statement
printf("sql: %s\n", sql.c_str());
//get link to database object
if (sqlite3_open("C:\ProgramData\PROISER\ISASPSUS\datastore\dsfile.db", &db) != SQLITE_OK) {
printf("ERROR: can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return found;
}
// compile sql statement to binary
if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL) != SQLITE_OK) {
printf("ERROR: while compiling sql: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
sqlite3_finalize(stmt);
return found;
}
// execute sql statement, and while there are rows returned, print ID
int ret_code = 0;
while ((ret_code = sqlite3_step(stmt)) == SQLITE_ROW) {
printf("TEST: ID = %d\n", sqlite3_column_int(stmt, 0));
found = true;
}
if (ret_code != SQLITE_DONE) {
//this error handling could be done better, but it works
printf("ERROR: while performing sql: %s\n", sqlite3_errmsg(db));
printf("ret_code = %d\n", ret_code);
}
printf("entry %s\n", found ? "found" : "not found");
//release resources
sqlite3_finalize(stmt);
sqlite3_close(db);
return found;
}
The errors that are being returned are from the category Compiler Error C4129.
I cant reach a solution. If you could help me I would appreciate it.
I could correct above mistake by puting "\\" in all the parts of the path in sqlite3_open. Beside that, another error poped up about a entry point that must be defined, refering to
if (sqlite3_open("C:\ProgramData\PROISER\ISASPSUS\datastore\dsfile.db", &db) != SQLITE_OK) {
printf("ERROR: can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return found;`
Also what i want to know is if with this piece of code is enough for opening and reading the database. Im starting with sqlite3 and what i want to do next is exporting its content to an excel file.
Someone recommend me using the exact app for the cause that is native to sqlite3 and is like a cmd.However, i would rather build a script for this purpose instead of using a cmd.
I am using SQLite3 header files in my C++ program and trying to create a table and insert data onto it, it works fine on a regular input.
It shows error when I use it in a C++ loop with changing variables.
I am using the database to insert my reading from RS-232.
Here is my code:
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
std::string sql_str;
std::ostringstream temp;
std::string command;
/* Open database */
rc = sqlite3_open("test_1.db", &db);
if (rc){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
}
else{
fprintf(stderr, "Opened database successfully\n");
}
std::string str;
std::ostringstream oss;
oss << id_count; // stornig the primary id int values into a string
str = "INSERT INTO M_DATA (ID, DETAILS) VALUES(";
str += oss.str(); //copying the int primary id
str += ", '";
std::string str_t1(szBuffer); //Copying character aray to a string
str += str_t1; //concatening the string
str += "');";
//printing what the database takes
//output_file << std::endl << str << std::endl;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0
sql = writable;
output_file << std::endl << "## SQL COMMAND : " << sql << "#" << std::endl;
// don't forget to free the string after finished using it
delete[] writable;
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
output_file << std::endl << "** SQL ERROR : " << zErrMsg << "*" << std::endl;
sqlite3_free(zErrMsg);
}
else{
fprintf(stdout, "Records created successfully\n");
}
// _sleep(3000);
sqlite3_close(db);
My issue is I have a szBuffer which changes everytime, and I have to insert it as a new entry into the table.
Is there a way to increment the Primary Key and store my string into it?
The sz buffer at a single line will give data like: For Ex:
szBuffer : ersion = 1 [SPI]: MinorVersion = 2 [SPI]: Real Time
= 1434260351 [SPI]: SR # = SBB-ST1000090
The SQL command in the string I pass is like this:
SQL COMMAND : INSERT INTO M_DATA (ID, DETAILS) VALUES(9,
'ersion = 1 [SPI]: MinorVersion = 2 [SPI]: Real Time = 1434260351
[SPI]: SR # = SBB-ST1000090');
The Error which I get is like:
SQL ERROR : near "¸”_": syntax error
I am not sure if I am doing this right or wrong.
Can we use the insert statement in a loop? Am I passing the string the right way? (It looks correct to me when I print it out.)
But why do I get an error?
Is there any better way to enter my data?
I am very new to this so I tried search the internet, but no one is doing it the way I did it.
Please help.
Many Thanks.
(Almost) never build a SQL statement via string concatenation. Use a prepared statement and bind the parameter values.
// Prepare the statement
sqlite3_stmt* stmt;
int result = sqlite3_prepare_v2(db, "INSERT INTO M_DATA (ID, DETAILS) VALUES(?, ?);", -1, &stmt, nullptr);
// TODO: Handle when result != SQLITE_OK
while(/* whatever you wanted to loop on */)
{
// Bind in the parameter values
result = sqlite3_bind_int(stmt, 1, id_count);
// TODO: Handle when result != SQLITE_OK
result = sqlite3_bind_text(stmt, 2, szBuffer, -1, SQLITE_STATIC);
// TODO: Handle when result != SQLITE_OK
// Invoke the statement
result = sqlite3_step(stmt);
// TODO: Handle when result != SQLITE_OK
// Reset the statement to allow binding variables on the next iteration
result = sqlite3_reset(stmt);
}
// Release the statement
sqlite3_finalize(stmt);
I have a problem with an INSERT INTO command using SQLite3 in C++.
I want to save different strings in an existing database.
I already tested it with static values. There it works fine.
But when I want to save generated strings in that database, the database is empty every time.
Thats my c++ code:
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
#include <string>
#include <sstream>
#include "createdb.h"
using namespace std;
/* Converts Strings into quotes */
string quotesql( const string& s ) {
return string("'") + s + string("'");
}
double addquery(string name, string email, double temp, double humidy, double intervall)
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql_insert;
double i = 1;
/* Convert Double into String */
stringstream NumberString;
NumberString << temp;
string stringtemp = NumberString.str();
NumberString << humidy;
string stringhumidy = NumberString.str();
NumberString << intervall;
string stringintervall = NumberString.str();
NumberString << i;
string stringi = NumberString.str();
string stringname = name;
string stringemail = email;
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
}else{
fprintf(stderr, "Opened database successfully\n");
}
/* This INSERT INTO command works fine
sql_insert = "INSERT INTO einstellungen (ID,EMAIL,NAME,TEMP,INTERVALL,HUMIDY)" \
"VALUES (1, 'user#test.com', 'John Doe', -5, 50, 20 );"; */
/*
/* This INSERT INTO command doesn't work */
string sqlstatement =
"INSERT INTO einstellungen (ID, EMAIL, NAME, TEMP, INTERVALL, HUMIDY) VALUES ("
+ quotesql(stringi) + ","
+ quotesql(stringemail) + ","
+ quotesql(stringname) + ","
+ quotesql(stringtemp) + ","
+ quotesql(stringintervall) + ","
+ quotesql(stringhumidy) + ");";
*/
/* Execute SQL statement */
rc = sqlite3_exec(db, sql_insert, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}else{
fprintf(stdout, "Einstellungen gespeichert\n");
}
sqlite3_close(db);
return 0;
}
Does anybody know where I make a mistake?
Thanks a lot :-)
I create some cout commands after each string command.
Here is the result:
I build some cout commands between each string command:
Here the result:
Datenbank wird nun angelegt
Datenbank erfolgreich angelegt
Datenbank erfolgreich initalisiert
Stringtemp: -5
Strinhumidy: 25
Stringintervall: 500
Stringi: 1
Stringname: John Doe
Stringemail: john.doe#online.de
Opened database successfully
INSERT INTO einstellungen (ID,EMAIL,NAME,TEMP,INTERVALL,HUMIDY)VALUES
(1,'john.doe#online.de','John Doe',-5,500,25);
Einstellungen gespeichert
Your numerical values such as stringhumidy shouldn't be enclosed in quotes. If you still have a problem then print somewhere the value of the sqlstatement in order to find what the error is.
I found my mistake!
I added the following line:
char * buffer = new char[sqlstatement.length()];
strcpy(buffer,sqlstatement.c_str());
So i converted the sqlstatement (string) into the required char operator
my C++ program reads a file with sql query and tries to execute it. When I execute the query using phpmyadmin, it works, but when executed in my program, it ends up with the following error:
Code:
ifstream create_file ("create.sql");
if (create_file.is_open())
{
char * create;
int length;
create_file.seekg (0, ios::end);
length = create_file.tellg();
create_file.seekg (0, ios::beg);
create = new char [length];
create_file.read (create,length);
create_file.close();
cout << "Executing query: " << endl;
cout.write (create,length);
cout << "EOF query" << endl;
if(mysql_query(mysql, "CREATE DATABASE grant_db")) {
fprintf(stderr, "Failed to create database: Error: %s\n",
mysql_error(mysql));
}
if(mysql_select_db(mysql, "grant_db")) {
fprintf(stderr, "Failed to select database: Error: %s\n",
mysql_error(mysql));
}
if(mysql_query(mysql, create)) {
fprintf(stderr, "Failed to create table: Error: %s\n",
mysql_error(mysql));
mysql_query(mysql, "DROP DATABASE grant_db");
}
delete[] create;
} else cout << "Unable to open file 'create.sql'.";
Thanks for your help!
You can't put multiple statements in a single mysql_query call. You need to execute them one at a time, by default at least. See the mysql_query docs.
My bet would be that it doesn't handle the /* ... */ comments. Try using -- comments instead.