ODBC: How to bind a empty string?

笑着哭i 提交于 2019-12-23 12:04:03

问题


I have a code that binds a string to an ODBC statement that looks like this

std::string v = "...";
SQLBindParameter(stmt, c, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR,
                          v.size(), 0, &v[0], v.size(), 0)

It works for any regular string, but not for empty string. I get an error message instead:

Error: [Microsoft][ODBC SQL Server Driver]Invalid precision value

I changed the function call to this

 SQLBindParameter(stmt, c, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR,
                              std::max<SQLUINTEGER>(v.size(), 1), 0, &v[0], v.size(), 0)

And now empty string can be inserted, yet it is converted into a space instead of an empty string.

I don't want to insert a NULL value because many SQL statements become counter-intuitive when NULL is encountered. Is any way to bind an empty string at all?

(The database engine is SQL Server 2005 with ODBC3)


回答1:


Empty strings and strings with one space are treated the same in CHAR fields in most DBs, including SQLServer (e.g. see SQL Server 2008 Empty String vs. Space and a MicroSoft explanation that this is part of the SQL-92 spec here: http://support.microsoft.com/kb/316626).

So your modified call actually works correctly.

This is the same way someone else reported solving this problem at http://austinfrance.wordpress.com/2012/02/27/odbc-sqlbindparameter-hy104-howto-bind-an-empty-string-to-an-sql_varchar/

So to allow the empty (zero length) C string to be bound, we need to simply bind it to a parameter of at lease size 1.



来源:https://stackoverflow.com/questions/24545494/odbc-how-to-bind-a-empty-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!