tcl tdbc :: odbc包并将参数传递给查询

时间:2017-03-05 22:40:34

标签: tcl

这是我第一次尝试使用tdbc包(ODBC连接),我无法弄清楚如何将参数传递给查询。这是代码:

set dsnName dsn1
set username user1
set password xxxxx
set connStr "DSN=$dsnName; UID=$username; PWD=$password;"
tdbc::odbc::connection create db $connStr

set rows [db allrows {SELECT DISTINCT [Address] FROM [Customers] WHERE [Apt Number]='3-b'}]

这很有效。但是,我想将'3-b'传递给查询。所以我试过了:

set queryValues [dict create apt 3-b]
set rows [db allrows {SELECT DISTINCT [Address] FROM [Customers] WHERE [Apt Number]=':apt'} $queryValues]

但这给了我一个错误([Microsoft] [ODBC SQL Server驱动程序]字符串数据,右截断)或类似的东西。 我试过不同的格式,什么都没有用。我做错了什么?

(根据格伦的回答,我也尝试过:

set stmt [db prepare {SELECT DISTINCT [Address] FROM [Customers] WHERE [Apt Number]=:apt}]
set params [dict create apt "3-b"]
set rows [$stmt allrows $params]

相同错误([1] [Microsoft] [ODBC SQL Server驱动程序]字符串数据,右截断)

但这是有效的。

 set stmt [db prepare {SELECT DISTINCT [Address] FROM [Customers] WHERE [Apt Number]='3-b'}]
set rows [$stmt allrows]

我还必须补充一点,tclodbc包在这里运行正常。请参阅以下代码

package require tclodbc
#<connect to database>
#query
set aptNo "3-b"
set query "SELECT DISTINCT \[Address\] FROM \[Customers\] WHERE \[Apt Number\]=?"
set dbResult [$dbConn $query [list $aptNo]]

在tclodbc包中正常工作,但类似的代码在tdbc包中失败。

- 苏雷什

1 个答案:

答案 0 :(得分:0)

您需要使用prepared statement

# note, no quotes around the placeholder param name.
set stmt [db prepare {SELECT DISTINCT [Address] FROM [Customers] WHERE [Apt Number]=:apt}]
set params [dict create apt "3-b"]
set rows [$stmt allrows $params]

或者你可以创建一个&#34; apt&#34;局部变量:

set apt "3-b"
set rows [$stmt allrows]