Cannot connect to On-Premises SQL Server Express Instance with go-mssqldb - sql-server

I have ported a ETL utility I wrote over from C# to Go that performs a reporting task. The C# app is able to connect to the SQL Express server just fine but the Go app is struggling to find the named instance of SQLEXPRESS.
I have used both versions:
server=<server>\<instance>;user id=<user>;password=<passw>;database=<database>;
sqlserver://<user>:<passw>#<server>/<instance>?database=<database>
...in various iterations when executing:
db, err := sql.Open("sqlserver", connString)
if err != nil {
panic(err)
}
... and in both cases I get the the following error back:
no instance matching 'SQLEXPRESS' returned from host 'localhost'

Related

Connect to SQL Server using GORM and Windows Authentication

I am trying to connect to a SQL Server database using gorm. I am able to connect through Golang datasource with the following connection string:
jdbc:jtds:sqlserver://{HOST}:1433/{DATABASE_NAME};useNTLMv2=true;domain={DOMAIN};encrypt=true;trustServerCertificate=true;instance={INSTANCE}
I am trying the following dsn value in gorm:
sqlserver://{USER}:{PASS}#{HOST}:1433?database={DATABASE_NAME};trusted+connection=yes
But I am getting login failed, am I missing something?

Unable to connect .NET Core MVC Web API with SQL Server on Linux

I am using .NET Core MVC API (.NET Core 6.0), actually just C# in general.
I need to deploy a .NET API on a linux server. However, it seems to that I can't connect to the SQL Server that is running on the same server.
This is the error from .NET
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
An unhandled exception has occurred while executing the request.
System.Exception: Cannot connect to SQL Server Browser. Ensure SQL Server Browser has been started.
---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (00000001, 11): Resource temporarily unavailable
at System.Net.Dns.GetHostEntryOrAddressesCore(String hostName, Boolean justAddresses, AddressFamily addressFamily, ValueStopwatch stopwatch)
This is the error I get from curl
{"error":true,"message":"Cannot connect to SQL Server Browser. Ensure SQL Server Browser has been started."}
Keep in mind that both the API and the database are on the same server.
I think the problem comes from .NET. I am able to connect to the database on the server using the API locally.
This is the connection string in my appsettings.json
"ConnectionStrings": {
"ConnStr": "Data Source=<PUBLICIP>;Initial Catalog=<DBNAME>;User Id=<USER>;Password=<PASS>;Integrated Security=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",=
"lockerConStr": ""
}
Any help would be greatly appreciated!
Things I have tried:
Changed Data Source to (local) - (doesn't work)
Added Encrypt= false;Trusted_connection=True; - (doesn't work)
Connect to the SQL Server from local version of the .NET API (successful)
Connect to the SQL Server using a python script running from the same server (successful)
Specified Driver in the connection string (doesn't work)
The python script (not sure if this would help)
import pyodbc
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=<PUBLICIP>;'
'Database=<DBNAME>;'
'UID=<USER>;'
'PWD=<PWD>;'
'Trusted_Connection=no;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM users')
I deleted the whole project on the server and cloned the git back.
After carefully reading the error, I noticed that it's running using my local connection string (not sure why, I changed the connection string on the server). I also rebuilt the solution and republished it a few times. Not sure what changed.
But I finally got it to work!

How to connect to SQL Server using Windows Auth?

I am currently using this example to connect to SQL Server using Go:
Create Go apps
Here is the example I am using:
package main
import (
_ "github.com/denisenkom/go-mssqldb"
"database/sql"
"context"
"log"
"fmt"
)
// Replace with your own connection parameters
var server = "localhost"
var port = 1433
var user = "sa"
var password = "your_password"
var db *sql.DB
func main() {
var err error
// Create connection string
connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d",
server, user, password, port)
// Create connection pool
db, err = sql.Open("sqlserver", connString)
if err != nil {
log.Fatal("Error creating connection pool: " + err.Error())
}
log.Printf("Connected!\n")
// Close the database connection pool after program executes
defer db.Close()
SelectVersion()
}
Is there any known way to use Windows Authentication to connect to SQL Server? I have tried adding "Trusted_Connection=yes" and removing the username/password.
I have Googled around but have not found any Go Packages that have this option.
As I posted earlier...
"trusted_connection=yes" did work. I just entered it wrong.
In my workplace we are using GORM which uses go-mssqldb to connect to the SQL Server. The following connection string format worked for us:
sqlserver://DATABASE_HOSTNAME:1433?database=DATABASE_NAME&trusted+connection=yes&app+name=APPLICATION_NAME
Your client side setup was correct. Did you add the windows user account to to the Database? I have done this multiple time without issues. Make sure your windows auth is enabled in your Db and the user has sufficient previlages.
steps to connect to sql server using windows authenticaton

creating access to SQL Server Native Client OLE DB provider using CoCreateInstance fails with 80040154 error

I am trying to obtain access to SQL Server Native Client OLE DB provider using :
hr = CoCreateInstance(CLSID_SQLNCLI11, NULL, CLSCTX_INPROC_SERVER, IID_IDBInitialize,
(void **) &PIDBInitialize);
and this fails with 80040154 error.
I am using sqlserver 2012 and everything worked perfectly fine as long as my application was running on the same machine as sql server was installed but now that the app is deployed in a different environment in which the app runs on a separate server than the server which has the database and sql server I am failing with this error even though the sql server version on the target server is same as mine.
Any ideas why would this behave in such way?
I appriciate your response.
Thats REGDB_E_CLASSNOTREG so CLSID_SQLNCLI11 is not available, download and install the redistributable package for the Native Client (Matching the bitness of your application).
Download.

Unable to connect to MS SQL Server using Go

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")
}
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:
Open up SQL Server Configuration Manager.
Expand "SQL Server Network Configuration" on the tree on the left.
Click on "Protocols for SQLEXPRESS (or whatever name your DB has)"
In the main menu, make sure "TCP/IP" is enabled. If not, right-click on it and select "Enable".
Right-click on the "TCP/IP" again and select properties.
Select the "IP Addresses" tab and scroll all the way down.
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
This https://code.google.com/p/odbc/ driver works with MS SQL Server for me.
Alex

Resources