只是试图在SQL db中存储blob数据(int array [128])。

我的sql语句有问题

 // temp is a 512 byte char array that was memcpyed from a 512 byte int array
 sprintf(insert, "insert into SiftFeatures(M_Id, FeatureData) values((Select M_Id from Master where M_Id='1'), 'Ab345' )" , temp);
 if(mysql_query(con, insert)){
    fprintf(stderr, "%s\n", mysql_error(con));
 }


这里的问题是当我这样做时,char *终止于一个空字节(即0000 0000)
我真的不知道如何执行此sql执行语句。还有另一种方法吗?

最佳答案

您需要转义数据。这是一个粗糙的例子:

// your array which is to become a blob
int array[128];

// compute the maximum size of the escaped blob
int escaped_size = 2 * sizeof(array) + 1;

// get some storage for the escaped blob
char chunk[escaped_size];

// now escape the blob into the storage
mysql_real_escape_string(con, chunk, (const char*)array, sizeof(array));

// form a query string template and measure its length
const char* query_template = "INSERT INTO SiftFeatures(M_Id, FeatureData) VALUES((Select M_Id from Master where M_Id='1'), '%s')";
size_t template_len = strlen(query_template);

// provide enough space to hold the rendered query template
// (i.e. the query text and the escaped blob)
int query_buffer_len = template_len + escaped_size;
char query[query_buffer_len];

// now render the final query string (template plus escaped blob)
int query_len = snprintf(query, query_buffer_len, query_template, chunk);

// execute the query
mysql_real_query(con, query, query_len);

09-09 23:07
查看更多