SQLBindParameter使用C ++和SQL Native Client准备SQLPutData
时间:2020-03-05 18:59:03 来源:igfitidea点击:
我正在尝试使用SQLBindParameter来准备我的驱动程序以通过SQLPutData进行输入。数据库中的字段是" TEXT"字段。我的功能是根据MS的示例制作的:
http://msdn.microsoft.com/zh-cn/library/ms713824(VS.85).aspx。
我已经设置了环境,建立了连接,并成功准备了我的语句,但是当我调用SQLBindParam(使用下面的代码)时,它始终无法报告:[Microsoft] [SQL Native Client]无效的精度值`
int col_num = 1; SQLINTEGER length = very_long_string.length( ); retcode = SQLBindParameter( StatementHandle, col_num, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, NULL, NULL, (SQLPOINTER) col_num, NULL, &length );
上面的代码依赖于使用中的驱动程序,它为SQLGetInfo中的SQL_NEED_LONG_DATA_LEN信息类型返回" N"。我的司机返回" Y"。如何绑定以便可以使用" SQLPutData"?
解决方案
回答
我们将传递NULL作为缓冲区长度,这是一个in / out参数,应为col_num参数的大小。另外,我们应该为ColumnSize或者DecimalDigits参数传递一个值。
http://msdn.microsoft.com/zh-cn/library/ms710963(VS.85).aspx
回答
尽管它看起来不像文档的示例代码,但我发现了以下解决方案可用于我要完成的工作。感谢gbjbaanb使我重新测试对SQLBindParameter的输入组合。
SQLINTEGER length; RETCODE retcode = SQLBindParameter( StatementHandle, col_num, // position of the parameter in the query SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, data_length, // size of our data NULL, // decimal precision: not used our data types &my_string, // SQLParamData will return this value later to indicate what data it's looking for so let's pass in the address of our std::string data_length, &length ); // it needs a length buffer // length in the following operation must still exist when SQLExecDirect or SQLExecute is called // in my code, I used a pointer on the heap for this. length = SQL_LEN_DATA_AT_EXEC( data_length );
执行语句后,可以使用SQLParamData确定SQL希望我们发送的数据,如下所示:
std::string* my_string; // set string pointer to value given to SQLBindParameter retcode = SQLParamData( StatementHandle, (SQLPOINTER*) &my_string );
最后,使用SQLPutData将字符串的内容发送到SQL:
// send data in chunks until everything is sent SQLINTEGER len; for ( int i(0); i < my_string->length( ); i += CHUNK_SIZE ) { std::string substr = my_string->substr( i, CHUNK_SIZE ); len = substr.length( ); retcode = SQLPutData( StatementHandle, (SQLPOINTER) substr.c_str( ), len ); }