Amir Mohsen
Amir Mohsen

Reputation: 851

How to get database tables list from MySQL (SHOW TABLES)

I have a problem with getting database table list (SHOW TABLES) in Go.

I use this packages

database/sql

gopkg.in/gorp.v1

github.com/ziutek/mymysql/godrv

and connect to MYSQL by this code:

db, err := sql.Open(
    "mymysql",
    "tcp:127.0.0.1:3306*test/root/root")
if err != nil {
    panic(err)
}

dbmap := &DbMap{Conn:&gorp.DbMap{Db: db}}

And I use this code to get list of tables

result, _ := dbmap.Exec("SHOW TABLES")

But result is empty!

Upvotes: 4

Views: 11407

Answers (3)

Victor Meireles
Victor Meireles

Reputation: 1

To anyone in the future, I'm achive my goal using DB.Migrator().GetTables()

Upvotes: -1

vladkras
vladkras

Reputation: 17228

I use classic go-sql-driver/mysql:

db, _ := sql.Open("mysql", "root:qwerty@/dbname")

res, _ := db.Query("SHOW TABLES")

var table string

for res.Next() {
    res.Scan(&table)
    fmt.Println(table)
}

PS don't ignore errors! This is only an example

Upvotes: 11

Amir Mohsen
Amir Mohsen

Reputation: 851

I'm trying this code and work successfully. I create a list of string and use Select query to get list of database tables.

tables := []string{}
dbmap.Select(&tables, "SHOW TABLES")
fmt.Println(tables)

Upvotes: 4

Related Questions