快捷搜索:  as  2018  FtCWSyGV  С˵  test  xxx  Ψһ  w3viyKQx

和记娱h188下载app:用mysql存储二进制数据流



近日一项目碰到必要在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

#include

#include

#include

#define INSERT_QUERY "INSERT INTO bintest(id, data) VALUES(4, ?)"

void test()

{

MYSQL_BIND bind[1];

unsigned longlength;

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(my和记娱h188下载appsql);

if (!stmt)

{

f和记娱h188下载appprintf(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_TY和记娱h188下载appPE_TINY;

bind[0].buffer_type = MYSQL_TYPE_BLOB和记娱h188下载app;

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;

/*和记娱h188下载app 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;

}

您可能还会对下面的文章感兴趣: