1

我想做一个 sql 查询并且只得到一个响应,虽然它应该是五个。

只有第一个被放入通道

bind pub "-|-" !sqlpre pub:test:sqlpre
proc pub:test:sqlpre { nick host handle channel arg } {

set searchname [lindex [split $arg] 0]

sqlite3 data /home/local/test.db
set result [data eval {SELECT * FROM folders WHERE name LIKE $searchname}]


if {[llength $result] == 0} {
    putnow "PRIVMSG $channel :Nothing found";
    return 0;
} else {
    set id [lindex $result 0];
    set source [lindex $result 1];
    set path [lindex $result 2];
    set name [lindex $result 3];

}
putnow "PRIVMSG $channel :$id $source $path $name"
}

问题现在在这里:

1 aa /tmp searchtest1

但这里应该是这样的:

1 aa /tmp searchtest1
4 ab /tmp searchtest1
17 ac /tmp searchtest1
18 ad /tmp searchtest1
9 ae /tmp searchtest1
4

1 回答 1

1

您需要数据库连接方法的迭代形式eval。您可能还应该明确命名您的列,而不是使用*SQL通常不能保证它们默认的顺序。(主键可能是第一位的。)

package require sqlite3
# Put this outside the procedure; it can be shared
sqlite3 data /home/local/test.db

bind pub "-|-" !sqlpre pub:test:sqlpre
proc pub:test:sqlpre { nick host handle channel arg } {
    set searchname [lindex [split $arg] 0]
    set found no

    # For each matching row...
    data eval {
        -- You can use “sqlExpr AS theName” to change the names of things
        SELECT id, source, path, name 
        FROM folders 
        WHERE name LIKE $searchname
    } row {
        # The 'row' above names a Tcl array that holds the result row data.
        # This means we can use the values out of it directly.
        putnow "PRIVMSG $channel :$row(id) $row(source) $row(path) $row(name)"

        # Remember that we have found something
        set found yes
    }

    # If we didn't find anything, tell the user
    if {!$found} {
        putnow "PRIVMSG $channel :Nothing found"
    }
}

请注意,我们在许多用户操作之间共享数据库连接。这是一种很好的做法,因为这意味着我们正在共享资源。为了便于阅读,SQL 查询语句现在包含多行。可读性很好。

于 2020-04-19T17:18:41.553 回答