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

huangapple go评论116阅读模式
英文:

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

问题

我在Go语言中获取数据库表列表(SHOW TABLES)时遇到了问题。

我使用了以下包:

  • database/sql
  • gopkg.in/gorp.v1
  • github.com/ziutek/mymysql/godrv

并通过以下代码连接到MYSQL:

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}}

我使用以下代码获取表列表:

result, _ := dbmap.Exec("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!

答案1

得分: 10

我使用经典的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)
}

// 请不要忽略错误!这只是一个示例

请注意,这是一个示例代码,不要忽略错误。

英文:

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

答案2

得分: 4

我正在尝试这段代码,并且成功地运行了。我创建了一个字符串列表,并使用Select查询来获取数据库表的列表。

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

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)

答案3

得分: -1

对于未来的任何人,我使用DB.Migrator().GetTables()实现了我的目标。

英文:

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

huangapple
  • 本文由 发表于 2017年5月10日 13:36:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/43884295.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定