我见过几次关于PHP (下面是一个例子)的问题。答案通常是“停止使用魔法引号”。但是,我在C中遇到了这个问题。当我将二进制数据插入到MySQL数据库中的blob中时,通过mysql_real_escape_string()
运行它后,BLOB中会出现一些5c ('\')字符。这会扰乱数据,使其无法使用。我怎样才能防止/解决这个问题呢?
#define CHUNK_SZ (1024*256)
void insertdb(int16_t *data, size_t size, size_t nmemb)
{
static int16_t *buf;
static unsigned long index;
static short initialized;
unsigned long i;
struct tm *info;
time_t rawtime;
char dbuf[12];
char tbuf[12];
char *chunk;
if(initialized==0){
buf = (int16_t *) malloc(CHUNK_SZ);
initialized = 1;
}
if(index + (nmemb*size) + 1 >= CHUNK_SZ || do_exit == 1){
time(&rawtime);
info = localtime(&rawtime);
snprintf(dbuf, 16, "%d-%02d-%02d", 1900+info->tm_year, 1+info->tm_mon, info->tm_mday);
snprintf(tbuf, 16, "%02d:%02d:%02d", info->tm_hour, info->tm_min, info->tm_sec);
chunk = (char *) malloc(index*2+1);
mysql_real_escape_string(con, chunk, (char *) buf, index);
char *st = "INSERT INTO %s (date, time, tag, data) VALUES ('%s', '%s', %d, '%s')";
int len = strlen(st)+strlen(db_mon_table)+strlen(dbuf)+strlen(tbuf)+sizeof(tag)+index*2+1;
char *query = (char *) malloc(len);
int qlen = snprintf(query, len, st, our_table, dbuf, tbuf, tag, chunk);
if(mysql_real_query(con, query, qlen)){
fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}
free(chunk);
index = 0;
} else {
memcpy((void *) buf+index, (void *) data, nmemb*size);
index += (nmemb*size);
}
return;
}
编辑:请看这里。他们使用相同的函数来转义二进制数据(从图像),插入它,然后从数据库获得相同的图像。对于我来说,我的二进制数据与图像的二进制数据有些不同,这对我来说是毫无意义的。
发布于 2014-12-22 12:08:35
如果要插入BLOB列,那么应该将其表示为HEX字符串,而不是通过mysql_real_escape_string()
转义数据。您必须弄清楚如何将您的int16_t
数据编码成所需的字节序列,因为至少您有一个字节顺序问题要处理(但是如果您控制编码和解码,那么只需要使它们匹配)。
或者,如果数据是真正的文本数据,而不是二进制数据,那么列的类型应该是Text
而不是BLOB
。在这种情况下,您应该继续使用一个普通的SQL字符串和mysql_real_escape_string()
。
https://stackoverflow.com/questions/27608240
复制相似问题