[英]c++ float to sql server DECIMAL correct conversion
I am creating an application in native c++ using odbc. 我正在使用odbc在本机c ++中创建一个应用程序。 I am calling on to a sql server stored procedure that has a decimal parameter. 我正在调用具有十进制参数的sql server存储过程。 I am passing a float to that parameter. 我将浮点数传递给该参数。 The code so far: 到目前为止的代码:
SQLDECIMAL *sql_param = new SQLDECIMAL( param);
if( SQL_ERROR == ( result = SQLBindParameter( statement_handle, 5, SQL_PARAM_INPUT, SQL_C_FLOAT, SQL_DECIMAL, 12, 6, sql_param, 0, NULL ) ) ){
std::wstring error = get_error_message( SQL_HANDLE_STMT, statement_handle );
throw GenericException( error );
}
param is a float. 参数是一个浮点数。
What gets stored on the table is always 0 instead of the real value which is 1.45. 存储在表上的内容始终为0,而不是1.45的实际值。 I'm guessing some conversion is taking place but I can't figured out the correct conversion. 我猜正在进行一些转换,但是我找不到正确的转换。 SQL_C_FLOAT -> SQL_DECIMAL? SQL_C_FLOAT-> SQL_DECIMAL?
SQLRETURN SQLBindParameter(
SQLHSTMT StatementHandle,
SQLUSMALLINT ParameterNumber,
SQLSMALLINT InputOutputType,
SQLSMALLINT ValueType,
SQLSMALLINT ParameterType,
SQLULEN ColumnSize,
SQLSMALLINT DecimalDigits,
SQLPOINTER ParameterValuePtr,
SQLLEN BufferLength,
SQLLEN * StrLen_or_IndPtr);
...
BufferLength
[Input/Output] Length of the ParameterValuePtr buffer in bytes.
You have specified BufferLength
as zero. 您已将BufferLength
指定为零。 Looking here , you can see the length of decimal for different precision values: 在这里 ,您可以看到不同精度值的小数长度:
Precision StorageBytes
1-9 5
10-19 9
20-28 13
29-38 17
Therefore, you need to call method SQLBindParameter
as: 因此,您需要将方法SQLBindParameter
调用为:
SQLBindParameter( statement_handle, 1, SQL_PARAM_INPUT, SQL_C_FLOAT, SQL_DECIMAL, 12, 6, sql_param, 5, NULL )
The SQLDECIMAL is your problem. SQLDECIMAL是您的问题。 According to http://publib.boulder.ibm.com/infocenter/soliddb/v6r3/index.jsp?topic=/com.ibm.swg.im.soliddb.programmer.doc/doc/s0005314.c.data.types.html it is a unsigned char [f]. 根据http://publib.boulder.ibm.com/infocenter/soliddb/v6r3/index.jsp?topic=/com.ibm.swg.im.soliddb.programmer.doc/doc/s0005314.c.data.types .html是无符号字符[f]。 I suggest something like: 我建议类似:
void bind_float(float* param) {
SQLBindParameter( statement_handle, 5, SQL_PARAM_INPUT, SQL_C_FLOAT, SQL_DECIMAL, 12, 6, param, 0, NULL ) ) );
}
I got it. 我知道了。 It shouldn't have been: SQLDECIMAL *sql_param = new SQLDECIMAL( param );
它不应该是: SQLDECIMAL *sql_param = new SQLDECIMAL( param );
it should have been: SQLDECIMAL *sql_param = (SQLDECIMAL *) param;
它应该是: SQLDECIMAL *sql_param = (SQLDECIMAL *) param;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.