SQLite中的INSERT INTO命令与C ++不起作用

时间:2014-10-05 09:26:50

标签: c++ sqlite

我在C ++中使用SQLite3时遇到INSERT INTO命令的问题。

我想在现有数据库中保存不同的字符串。 我已经用静态值测试了它。它工作得很好。 但是当我想在该数据库中保存生成的字符串时,数据库每次都是空的。

这就是我的c ++代码:

#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;
}

有人知道我在哪里弄错了吗?

非常感谢: - )

我在每个字符串命令后创建一些cout命令。 结果如下:

我在每个字符串命令之间构建了一些cout命令:

结果如下:

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

2 个答案:

答案 0 :(得分:0)

stringhumidy等数字值不应用引号括起来。如果您仍有问题,请在sqlstatement的某处打印,以便找出错误。

答案 1 :(得分:0)

我发现了我的错误!

我添加了以下行:

char * buffer = new char[sqlstatement.length()];
strcpy(buffer,sqlstatement.c_str());

所以我将sqlstatement(string)转换为必需的char运算符