ODBC:如何绑定一个空字符串? [英] ODBC: How to bind a empty string?

查看:77
本文介绍了ODBC:如何绑定一个空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将字符串绑定到看起来像这样的ODBC语句的代码

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:

错误:[Microsoft] [ODBC SQL Server驱动程序]无效的精度值

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

我将函数调用更改为此

 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.

我不想插入NULL值,因为遇到NULL时,许多SQL语句变得违反直觉.有没有办法绑定空字符串?

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?

(数据库引擎是带有ODBC3的SQL Server 2005)

(The database engine is SQL Server 2005 with ODBC3)

推荐答案

空字符串和带一个空格的字符串在包括SQLServer在内的大多数DB的CHAR字段中都被视为相同(例如,请参见 http://support.microsoft.com/kb/316626 ).

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.

这与其他人在 http://austinfrance.wordpress.com/2012/02/27/odbc-sqlbindparameter-hy104-howto-bind-an-empty-string-to- an-sql_varchar/

因此,要绑定空(零长度)的C字符串,我们需要 只需将其绑定到租约大小为1的参数即可.

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.

这篇关于ODBC:如何绑定一个空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆