【发布时间】:2018-07-18 15:46:15
【问题描述】:
我正在尝试使用程序其他区域给出的值以特定格式创建 char* 类型,VALUES() 括号内的值是程序给出的值。 格式应如下所示:
char* sql = "INSERT INTO RecurringEvents (title,description,duration,recurtype,startfrom,endingtype,dateend,occurences,venueid) " \
"VALUES ('title','description','duration','recurtype','startfrom','endingtype','dateend',occurences,venueid); "
如您所见,text 值必须在 ' ' 标点符号内,而 int 值则不用管,所以通常的命令可能是这样的:
"INSERT INTO RecurringEvents (title,description,duration,recurtype,startfrom,endingtype,dateend,occurences,venueid) " \
"VALUES ('thetitle','thedesc','theduration','recurtype','startfrom','enddddtype','dateend',2,4); ";
下面是需要这个的函数,这并不重要,但为了解释,它将事件的(类)数据全部转换为字符串/整数值,因此它们可以用来形成一个 INSERT 命令(这个是问题),然后在数据库上执行,一旦完成(并验证记录的合理性),将其添加到向量中并关闭数据库。
void addRecEvent(newRecurringEvent event, vector <newRecurringEvent> &events){
sqlite3 *db;
int rc;
char *sql;
int tableCheck;
char *zErrMsg = 0;
rc = sqlite3_open("data.sqlite", &db);
string title = event.getTitle();
string description = event.getDescription();
string duration = to_string(event.getDuration());
string recurType = recToString(event.getRecurType());
string startfrom = to_string( event.getStartFrom());
string endingtype = etypeToStr(event.getEndingType());
string dateend = to_string(event.getDateEnd());
int occurences = event.getOccurences();
int venueid = event.getVenuid();
/*CREATE INSERT COMMAND USING char*sql IN FORMAT REQUIRED*/
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); //execute the command
if (rc != SQLITE_OK){
cout << stderr << "SQL error: %s \n", zErrMsg;
}
else{
cout << stdout << "Records created succesfully";
events.push_back(event);
}
sqlite3_close(db);
}
我曾经尝试在另一个函数中以字符串形式创建格式(通过将值传递给它),然后将其作为 char* 返回,但遇到了文本字段上使用的单引号的问题 (如标题、描述等)。
抱歉,如果其中任何内容令人困惑,但为了简短起见,我只想按照代码的第一个 sn-p 中的格式形成一个字符序列,它使用给定的值来形成它的序列。感谢任何帮助,因为我是 C++ 新手。
【问题讨论】:
-
使用prepared statement 并根据类型绑定动态参数,然后执行语句。 binder 对数据进行了整理,更重要的是,安全地形成语句并避免 sql 注入风险。这是支持它的 sql 后端的普遍偏好(大多数都支持,包括 sqlite)。
-
您不能以特定格式创建
char*;由编译器决定如何表示char*。您的问题是关于char@ 的数组,它与指向char的指针不同。
标签: c++ sqlite type-conversion