1

I try to read out the table names of an Access database (aka. an mdb-file) in go. My code is pretty much a mixture of an example of how to use the go-driver and the stackoverflow answer on how to get the table names from an mdb file.

The result is the the text

get table names

on the command-line which means that the row log.Fatal("get table names", err) got triggered. But as a golang-beginner, i don't know why this happened because the error message seems to be empty, so i don't get any further information.

package main

import (
    "database/sql"
    "fmt"
    "log"
    _ "github.com/mattn/go-adodb"
)

func main() {
    mdbFilePath := "./register.mdb"

    db, err := openAccessDb(mdbFilePath)
    if err != nil {
        log.Fatal("open file error:", err)
    }

    tableNames, err := getTableNames(db)
    if err != nil {
        log.Fatal("get table names", err)
    }

    if len(tableNames) <= 0 {
        fmt.Println("no tables found in " + mdbFilePath)
        return
    }
    // print out all the table names
    for index, tableName := range tableNames {
        fmt.Printf("table {%d}: {%s}\n", index+1, tableName)
    }
}

func openAccessDb(mdbFilePath string) (*sql.DB, error) {
    db, err := sql.Open(
        "adodb",
        "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+mdbFilePath+";")
    return db, err
}

func getTableNames(db *sql.DB) ([]string, error) {
    rows, err := db.Query(
        `SELECT MSysObjects.Name AS table_name
        FROM MSysObjects
        WHERE (((Left([Name],1))<>"~")
        AND ((Left([Name],4))<>"MSys")
        AND ((MSysObjects.Type) In (1,4,6)))
        order by MSysObjects.Name`)
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    tableNames := make([]string, 4)
    for rows.Next() {
        var name string
        if err := rows.Scan(&name); err != nil {
            return nil, err
        }
        tableNames = append(tableNames, name)
    }
    if err := rows.Err(); err != nil {
        return nil, err
    }

    return tableNames, nil
}

UPDATE

the error comes from the select-query. But i don't know how to fix this as this comes, as mentioned, directly from another stackoverflow answer

Community
  • 1
  • 1
StephanS
  • 843
  • 1
  • 8
  • 20
  • Three spots in `getTableNames` could return non nil error. When you debugged this by adding log statements or using a debugger, which one was executed? – Carl Veazey Jun 04 '16 at 05:45
  • The first one with the Select-query. – StephanS Jun 06 '16 at 07:31
  • Adding "AND ((MSysObjects.Flags)=0)" as a constraint doesn't help. Maybe this goes back to a potential problem mentioned in the original stackoverflow topic: "MsysObjects are unsupported system tables and should not be used. Permissions on these tables outside of MS Access can be very chancy"? – StephanS Jun 06 '16 at 07:53

0 Answers0