package main
import (
"database/sql"
"fmt"
"strconv"
"time"
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/go-sql-driver/mysql"
)
type mt struct {
Num int
Mc sql.NullString
Renbm sql.NullInt32
Nrbm sql.NullInt32
Tgz sql.NullString
}
func main() {
page := 1
size := 10
const LAYOUT = "2006-01-02 15:04:05"
for true {
// 获取当前日期
now := time.Now()
flag := syncdata(page, size)
if flag == "success" {
fmt.Println("第" + strconv.Itoa(page) + "页同步完成")
fmt.Printf(now.Format(LAYOUT))
} else {
fmt.Println(flag)
break
}
page++
}
}
func syncdata(page, size int) string {
//SQL Server数据库连接
sqlserverDB, sqlserverErr := sql.Open("mssql", "server=10.10.10.142;user id=xxxxxxx;password=xxxxxxx;database=xxxxxxx;encrypt=disable")
if sqlserverErr != nil {
fmt.Println("连接SQL Server数据库错误: ", sqlserverErr.Error())
return "sql server错误"
}
defer sqlserverDB.Close()
//MySQL数据库连接
mysqlDB, mysqlErr := sql.Open("mysql", "root:xxxxxxx@tcp(127.0.0.1:3306)/test")
if mysqlErr != nil {
fmt.Println("连接MySQL数据库错误: ", mysqlErr.Error())
return "mysql 错误"
}
defer mysqlDB.Close()
// 从SQL Server数据库获取数据
offset := (page - 1) * size
rows, err := sqlserverDB.Query("SELECT num,mc,renbm,nrbm,tgz FROM mt ORDER BY num OFFSET " + strconv.Itoa(offset) + " ROWS FETCH NEXT " + strconv.Itoa(size) + " ROWS ONLY")
if err != nil {
fmt.Println("从SQL Server数据库获取数据错误:", err.Error())
return "从SQL Server数据库获取数据错误"
}
// 将数据插入MySQL数据库中
for rows.Next() {
var p mt
err = rows.Scan(&p.Num, &p.Mc, &p.Renbm, &p.Nrbm, &p.Tgz)
if err != nil {
fmt.Println("rows.Scan错误: ", err.Error())
return "rows.Scan错误"
}
_, err = mysqlDB.Exec("insert into mt(num,mc,renbm,nrbm,tgz) values(?,?,?,?,?)", p.Num, p.Mc, p.Renbm, p.Nrbm, p.Tgz)
if err != nil {
fmt.Println("插入MySQL数据库错误:", err.Error())
return "插入MySQL数据库错误"
}
}
return "success"
}
网友评论