skip to Main Content

I am playing around with Python in VS Code and I can’t seem to connect my code to my SQL Server database. Any suggestions? Below is the code and the error message I get when I run the code.

Code snippet:

from http import server
from os import name
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog, Tk, Label, Button
from PIL import Image, ImageTk
import tkinter.messagebox
import pyodbc
from datetime import datetime

#Initialize the database connection
server="MAURICE-PC\CLOCKIFY"
username="sa"
password="clockify"
database="master"
connection = pyodbc.connect("DRIVER={SQL Server};SERVER='MAURICE-PC\CLOCKIFY';DATABASE='master';UID='sa';PWD='clockify'")
cursor = connection.cursor()

Error code

Traceback (most recent call last):
  File "F:Visual Studio Code WorkspaceTime and Attendance.venvT&A.py", line 23, in <module>      
    connection = pyodbc.connect("DRIVER={SQL Server};SERVER='MAURICE-PC\CLOCKIFY';DATABASE='master';UID='sa';PWD='clockify'")
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (123)')

I enabled the remote connection via SSMS, I enabled the TCP/IP protocol in SQL Server Configuration Manager and allowed the port in the firewall’s incoming and outgoing connections

2

Answers


  1. Try replacing MAURICE-PCCLOCKIFY with ip server address.

    connection = pyodbc.connect("DRIVER={SQL Server};SERVER='192.168.X.X';DATABASE='master';UID='sa';PWD='clockify'")
    
    Login or Signup to reply.
  2. First, you define string variables but then you don’t use them in the actual connection string. I can’t test on my machine, If the SQL server set up correctly the following should work:

    connection = pyodbc.connect(f"DRIVER={{{SQL Server}}};SERVER={server};DATABASE={database};UID={username};PWD={password};")
    

    Also you might try using server ip for server address as @softghost suggested or localhost

    Also google "python formatted strings" to gain more knowledge how to read the code in your question and in my answer

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search