如何通过C变量将数据插入表中?

时间:2019-06-06 03:20:56

标签: c++ sql sqlite

我要在INTO表中插入数据,数据是C变量。

这是我当前的代码:

const char* sqlUpdateTable = "INSERT INTO MyTable 
                                          VALUES(25, 'String1', 'String2')
                                       ON CONFLICT (id) 
                                       DO 
                                         UPDATE SET name = 'New String';";

实际上,不仅'String1','String2'和'New String'需要是变量,而且id也是C / C ++变量。

id很长。

String1是double。

String2是int。

谢谢。

2 个答案:

答案 0 :(得分:0)

我认为这是我应该做的方式?

sqlite3_stmt* res;
const char* sqlInsert = "INSERT INTO MyTable VALUES(NULL, ?, ?);";

sqlite3_prepare_v2(db, sqlInsert, -1 , &res, 0);

const char* test1 = "ABC";
const char* test2 = "XYZ";

if (sqlite3_bind_text( res, 1, test1, 3, 0 ) != SQLITE_OK) 
{
    printf("\nError 1.\n");
}
if (sqlite3_bind_text(res, 2, test2, 3, 0) != SQLITE_OK)
{
    printf("\nError 2.\n");
}

int step = sqlite3_step(res);

答案 1 :(得分:-1)

使用sprintf()

char buffer [200];
double mydouble = 4.0;
long mylong = 2;
int myint = 4;
int n=sprintf (buffer, "INSERT INTO MyTable VALUES(25, '%f', '%i') ON CONFLICT (%l) DO UPDATE SET name = 'New String';", mydouble, myint , mylong);

请参阅: http://www.cplusplus.com/reference/cstdio/sprintf/