dongxu4580 2019-02-11 10:17
浏览 141

如何与本地主机上的mysql服务器建立连接?

I want to make a new connection with the sql server on localhost so that I can able to get the data from the sql server. but there is some problem while doing connection.

error :- [mysql] 2019/02/11 15:30:00 driver.go:81: net.Error from Dial()': dial tcp serverPort:3306: connect: connection timed out

And the code I'm using is

func ConnectMsqlDb() (db *sql.DB, err error) {
db, err = sql.Open("mysql", 
    fmt.Sprintf("%s:%s@tcp(%s:"+SqlDbPort+")/"+SqlDatabase, 
    SqlUsername, SqlPassword, SqlServerPort))
fmt.Println("OPEN", db, err)
if err != nil {
    return nil, err
}
//defer db.Close()
fmt.Println("PING:-", err)
err = db.Ping()
fmt.Println("PING:-", err)
if err != nil {
    return nil, err
}
return db, nil
}     

Can you help me to get out from this problem?

  • 写回答

1条回答 默认 最新

  • dqpciw9742 2019-02-11 14:20
    关注

    If you're trying to connect to a remote server you need its full address:

    <username>:<pw>@tcp(<HOST>:<port>)/<dbname>
    

    In your example I don't see the host anywhere, so it tries to connect to a server running on localhost (with port given by SqlServerPort).

    A simple connection example:

    func main() {
        db, err := sql.Open("mysql",
            "user:password@tcp(127.0.0.1:3306)/hello")
        if err != nil {
            log.Fatal(err)
        }
        defer db.Close()
    }
    

    You'll need to replace 127.0.0.1 with the actual IP address (or hostname) of your remote server.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?