I am new in Golang btw. I got confused when I try to connect gorm to remote SQL Server database.
In .NET I usually use this for web.config
<add name="DevSaveLog" connectionString="Data Source=11.111.1.111;Network Library=DBMSSOCN;Initial Catalog=Database_Log;User ID=user_log;Password=dhhdf127ihd" providerName="System.Data.SqlClient" />
And when I try to connect to gorm I tried like this
func Init() {
dsn := url.QueryEscape("sqlserver://user_log:dhhdf127ihd@http://11.111.1.111?database=Database_Log")
db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})
if err != nil {
panic("error connecting to database")
}
db.AutoMigrate()
}
And I got errors :
[error] failed to initialize database, got error unable to open tcp connection with host 'localhost:1433': dial tcp 127.0.0.1:1433: connectex: No connection could be made because the target machine actively refused it.
panic: error connecting to database
BTW I don't use the real URL in this question .Even I have declared the url server of sqlserver database it just keep reading localhost.
Any solutions?
Thanks :)
CodePudding user response:
I can see a few issues (the docs are a good place to start):
DSN String
sqlserver://user_log:dhhdf127ihd@http://11.111.1.111?database=Database_Log
is not a valid DSN (remove the http://
).
URL Encoding
url.QueryEscape("sqlserver://user_log:dhhdf127ihd@http://11.111.1.111?database=Database_Log")
returns sqlserver://user_log:dhhdf127ihd@http://11.111.1.111?database=Database_Log
.
This is not a valid URL and will not be correctly processed by github.com/denisenkom/go-mssqldb
which looks for a prefix of sqlserver://
. Remove the url.QueryEscape
.
In summary try something like:
dsn := "sqlserver://user_log:[email protected]?database=Database_Log"
db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})