# Sample:
#
# tclado db "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\temp\test.mdb"
# puts [db run "select * from Table1"]
#
# db configure -outputtype dict ;# dict or list(default)
# puts [db run "select * from Table1"]
#
package provide tclado 0.1

package require Itcl
namespace import ::itcl::*

package require tcom
::tcom::import "C:\Program Files\Common Files\System\ado\msado26.tlb"

class tclado {
    private variable _connectionString ""
    private variable con {}
    public variable nullString {}
    # list, dict
    public variable outputtype list
    
    constructor {connectionString} {
        set con [::tcom::ref createobject "ADODB.Connection"]
        set _connectionString $connectionString
        $con Open $connectionString
    }

    destructor {
        $con Close
    }
    
    public method run {sql} {
        set rst [$con Execute $sql]
        
        set rows [list]
        if {[$rst State] == 1} {
            while {[$rst EOF] == 0} {
                switch -- $outputtype {
                    list  { set row [list] }
                    dict  { set row [dict create] }
                    default {error "unknown type $outputtype"}
                }
    
                set fieldCount [[$rst Fields] Count]
                for {set i 0} {$i < $fieldCount} {incr i} {
                    set f [[$rst Fields] Item $i]
                    set name  [$f Name]
                    set value [$f Value]
                    if {$value eq "::tcom::NULL"} {
                        set value $nullString
                    } else {
                        if {[$f Type] == 7} {
                            set datetime [expr {int(-2209194000 + ($value * 86400))}]
                            set value [clock format $datetime -format "%Y-%m-%d %H:%M:%S"]
                        }
                    }
    
                    switch -- $outputtype {
                        list  { lappend row $value }
                        dict  { dict set row $name $value }
                    }
                }
                lappend rows $row
                $rst MoveNext
            }
        }
        return $rows
    }

    public method disconnect {} {
        $con Close
    }
}

CategoryTclTk


|New|Edit|Freeze|Diff|Backup|Attach|Copy|Rename|
Last-modified: 2012-01-24 (Tue) 17:56:06 (2368d)
HTML convert time: 0.007 sec.