近日一項目遇到需要在DB中存儲2進制數據流類型文件的問題,發現常用的MySQL API都用不了,再研究,方知有一套專門的API來干這種數據,功能相當強大的說。
以下即為范例代碼 --- 按照說明編譯即可用,稍加修改即可存儲2進制文件
view plaincopy to clipboardPRint?
/*   
mysql數據庫存儲二進制數據 linux  
 
用途: 用 mysql_stmt_send_long_data()來向blob字段寫入2進制數據流.  
 
注意點:需要注意的是bind結構的buffer_type字段,必須與要輸入的數據類型相符,  
如:只寫入一個long 數據,則用MYSQL_TYPE_LONG,寫入字符流,用MYSQL_TYPE_STRING,  
寫入2進制數據流,用MYSQL_TYPE_BLOB  
具體這個參數各字段的含義參見 mysql5.0手冊  
 
Compile: g++ -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient mysql_test.cpp  
 
準備工作:  
create database test;  
use test;  
CREATE TABLE `bintest` (  
`id` int(11) NOT NULL default '0',  
`data` blob  
) ENGINE=MyISAM;  
*/  
  
#include <mysql.h>   
#include <string.h>   
#include <stdio.h>   
#include <stdlib.h>   
  
  
#define INSERT_QUERY "INSERT INTO bintest(id, data) VALUES(4, ?)"   
  
void test()   
{   
MYSQL_BIND bind[1];   
unsigned long       length;   
  
char blog_data[100] = {0};   
memset(blog_data, 0x01, sizeof(blog_data));   
  
char* pos = blog_data;   
int size = 50;   
  
MYSQL *mysql = mysql_init(NULL);   
if (!mysql) return;    
if (!mysql_real_connect(mysql,   
   "192.168.xx.xxx",   
   "root",   
   "db_user_name",   
   "test",   
   3306, NULL, 0))    
{   
   int ret = mysql_errno(mysql);    
   mysql_close(mysql);   
   return;   
}   
  
MYSQL_STMT *stmt = mysql_stmt_init(mysql);   
if (!stmt)   
{   
   fprintf(stderr, " mysql_stmt_init(), out of memory/n");   
   exit(0);   
}   
if (mysql_stmt_prepare(stmt, INSERT_QUERY, strlen(INSERT_QUERY)))   
{   
   fprintf(stderr, "/n mysql_stmt_prepare(), INSERT failed");   
   fprintf(stderr, "/n %s", mysql_stmt_error(stmt));   
   exit(0);   
}   
memset(bind, 0, sizeof(bind));   
//bind[0].buffer_type= MYSQL_TYPE_STRING;   
//bind[0].buffer_type = MYSQL_TYPE_LONG;   
bind[0].buffer = blog_data;   
//bind[0].buffer_type = MYSQL_TYPE_TINY;   
bind[0].buffer_type = MYSQL_TYPE_BLOB;   
bind[0].length= &length;   
bind[0].is_null= 0;   
  
/* Bind the buffers */  
if (mysql_stmt_bind_param(stmt, bind))   
{   
   fprintf(stderr, "/n param bind failed");   
   fprintf(stderr, "/n %s", mysql_stmt_error(stmt));   
   exit(0);   
}   
  
int rc =0;   
/* Supply data in chunks to server */  
if (mysql_stmt_send_long_data(stmt,0, pos, size))   
{   
   fprintf(stderr, "/n send_long_data failed");   
   fprintf(stderr, "/n %s", mysql_stmt_error(stmt));   
   exit(0);   
}   
  
pos += size;   
  
/* Supply the next piece of data */  
if (mysql_stmt_send_long_data(stmt,0, pos, size))   
{   
   fprintf(stderr, "/n send_long_data failed");   
   fprintf(stderr, "/n %s", mysql_stmt_error(stmt));   
   exit(0);   
}   
  
/* Now, execute the query */  
if (mysql_stmt_execute(stmt))   
{   
   fprintf(stderr, "/n mysql_stmt_execute failed");   
   fprintf(stderr, "/n %s", mysql_stmt_error(stmt));   
   exit(0);   
}    
}   
  
  
int main()   
{   
test();   
//sleep(1);   
return 0;   
}  
新聞熱點
疑難解答