无法使用Go连接到MS SQL Server

I am trying to connect to sql server express using go and this sql driver "github.com/denisenkom/go-mssqldb"

Currently it calls open then stalls on the ping command, it never pings or returns an error.

I am using winauth and it works with sql management studio.

I have verified the database name, if I put a false one in, an error is generated and logged at the open step.

I have tried setting a really short connection time out but the same thing happens.

I have tried connecting to a remote sql server and it works correctly. The remote server is a developer version of sql server and had a name like xyz.abc.123 where my local sql express is called machine-name\sqlexpress.

Here is a sample program.

package main

import (
    "database/sql"
    _ "github.com/denisenkom/go-mssqldb"
    "log"
)

func main() {

    log.Println("Main:")

    log.Println("Opening")
    db, err := sql.Open("mssql", "server=Machine-Name\\SQLEXPRESS; database=MyDatabaseName;")

    if err != nil {
        log.Println("Open Failed: ", err.Error())
    }
    log.Println("Opened")

    log.Println("Pinging")
    err = db.Ping();
    if err != nil {
        log.Println("Failed to ping: ", err.Error())
    }

    log.Println("Pinged")
}

This https://code.google.com/p/odbc/ driver works with MS SQL Server for me.

Alex

I encountered this same issue not too long ago and after two days of researching I was able to fix the issue.

The confusing aspect seems to come from the fact that the go-mssqldb needs a parameter passed named "server" and in SQL Management Studio they have a clear reference to server in the connection properties:

Connection Properties

However, this is not the value go-mssqldb is looking for. It is looking for the actual server where the DB is installed. Meaning, if it is installed in your local PC this would be "localhost". If it's on another machine in your network, then this would be the corresponding IP address or server name

Another thing to keep in mind is that go-mssqldb needs a port to connect to the DB and if you don't provide one, it assumes the port is 1433. However, mine wasn't that value. In order to look for your port number:

  1. Open up SQL Server Configuration Manager.
  2. Expand "SQL Server Network Configuration" on the tree on the left.
  3. Click on "Protocols for SQLEXPRESS (or whatever name your DB has)"
  4. In the main menu, make sure "TCP/IP" is enabled. If not, right-click on it and select "Enable".
  5. Right-click on the "TCP/IP" again and select properties.
  6. Select the "IP Addresses" tab and scroll all the way down.
  7. Look at the section: "IPAll" and the number displayed in the "TCP Dynamic Ports" field is the correct port number.

SQL Server Configuration Manager

Finally, the command I ended up using to run my code ended up being:

sqlserver-agent -debug=true -server=localhost -port=62587 -user=Username -password=Password -database=DatabaseName