duandaoji3992 2017-02-11 16:54
浏览 216

如何使用GO连接到Linux中的MSSQL数据库

I have created and connected to an sql server on linux using this tutorial.

I am using golang and this driver. (https://github.com/denisenkom/go-mssqldb)

I am having problems connecting to the database using golang. I have specified a user as SA and a password. I have also written in the terminal "hostname" and got the hostname xxx. When I use that info to connect I get a 500 error.

conn, err := sql.Open("mssql", "server=xxx; id=SA; password=mypass; database=testdb)

Does this seem correct? I am a newbie so maybe I am missing something obvious?

  • 写回答

3条回答 默认 最新

  • dongshilve4392 2017-02-11 17:35
    关注

    In the Github example you can see how it work. You can follow those steps:

    var (
        server    string = "localhost" // for example
        user      string = "userdb"    // Database user
        password  string = "userpwd"   // User Password
        port      int    = 1433        // Database port
    )
    
    connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d", server, user, password, port)
    conn, err := sql.Open("mssql", connString)
    
    // Test if the connection is OK or not
    if err != nil {
        panic("Cannot connect to database")
    } else {
        fmt.Println("Connected!")
    
      }
    // Don't forget to close the connection to your database
    defer conn.Close()
    
    评论

报告相同问题?