我有八个Microsoft访问数据库,每个数据库有大约215个表,我需要将这些数据库转移到postgresql中,因此我使用了mdb-tools并导出了只有一步的方案;但是当它将表数据直接导出到postgres时进入postgresql我必须为每个表编写这个命令:
mdb-export -I postgres -q \' myaccessdatabase.mdb table-name | psql -d mypsqldatabase -U postgres -w -h localhost
所以我一直在尝试编写一个go命令程序,如下所示: 1.首先执行命令列出表名。这将是下一个命令的arg。 2.然后启动范围looop以执行导出tanle数据的命令,并将此命令的输出输入下一个命令。 3.此命令是psql,它将写入上一个命令的输出(这是sql insert statment)
package main
import (
"bufio"
"log"
"os"
"os/exec"
)
func main() {
// command to Collect tables name and list it to the next command
tablesname := exec.Command("mdb-tables", "-1", "myaccessdatabase.mdb")
// Run the command on each table name and get the output pipe/feed into the psql shell
for _, table := range tablesname {
ls := exec.Command("mdb-export", "-I", "postgres", "-q", "\'", "myaccessdatabase.mdb", table)
// | psql -d mydatabase -U postgres -w -h localhost command which will write each line from the output of previouse command's
visible := exec.Command("psql", "-d", "mypsqldatabase", "-U", "postgres", "-w", "-h", "localhost")
}
}
所以我试图将输出传递到下一个命令的标准输出并且无法实现它,同时我正在尝试使用goroutin和频道甚至无法提供一种方法将其变为最后一个命令。
非常感谢你。
答案 0 :(得分:1)
exec.Command
函数只创建命令,它不会执行它。
要从tablesname := exec.Command("mdb-tables", "-1", "myaccessdatabase.mdb")
获取输出,您需要运行命令并捕获其输出:
tablesname := exec.Command("mdb-tables", "-1", "myaccessdatabase.mdb")
//capture the output pipe of the command
outputStream := bufio.NewScanner(tablesname.StdoutPipe())
tablesname.Start() //Runs the command in the background
for outputStream.Scan() {
//Default scanner is a line-by-line scan, so this will advance to the next line
ls := exec.Command("mdb-export", "-I", "postgres", "-q", "\'", "myaccessdatabase.mdb", outputStream.Text())
ls.Run() //Blocks until command finishes execution
visible := exec.Command("psql", "-d", "mypsqldatabase", "-U", "postgres", "-w", "-h", "localhost")
visible.Run()
}
tablesname.Wait() //Cleanup
当心:对于数据库互动,exec
不是惯用代码。
SQL库允许与数据库直接交互:http://golang.org/pkg/database/sql/