Connecting Python to SQL Server with pymssql


In this post I’m going to talk about connecting Python to Microsoft’s SQL Server using the pymssql library on a Windows 11 computer. Be warned that these instructions are incomplete and I have not yet got this working on my machine.

I’m going to use the Anaconda Navigator to set up my Jupyter Notebook to write Python code. I have previously installed Python, Anaconda Navigator and SQL Server’s SQL Server Management Studio (SSMS). To follow along you only need a very basic knowledge of Python and SQL and those previously mentioned programs.

If you go into a new Jupyter Notebook and execute import pymssql in a cell, you will likely get an error stating that it can’t find the library. It’s not installed automatically. That’s okay because we will install that library here. If you get an error saying it can’t find pymssql, follow these steps, in Windows.

  1. Install the pymssql package. Go to a command prompt and enter pip install pymssql.
  2. Run Anaconda Navigator. Go to Environments. Not Installed drop down. Scroll down or search for pymssql. Check the check box for pymssql. Click the Apply button in the bottom right side. Wait.
  3. Check that it did in fact install properly by clicking the Installed drop down and search for pymssql. See the screenshot below.

Below is a partial screenshot of Anaconda Navigator after I have installed psmssql into Anaconda Navigator by first choosing uninstalled and the checking the checkbox for pymssql and waiting for it to install into Anaconda Navigator.

Connecting Python to SQL Server with pymssql

Connecting Python to SQL Server with pymssql

If you cannot connect, you may or may not need to open up TCP/IP to the server. You would need to go into SQL Server Configuration Manager. You may want to use a different library instead. Try pyodbc.

I was unable to get the connection to work.

Leave a Reply