Home computickets Connecting to a Database in Python

Connecting to a Database in Python

Author

Date

Category

I am trying to connect to the SQL server. Sample code below.
I get an error while connecting.

(‘IM002’, ‘[IM002] [Microsoft] [ODBC Driver Manager] Data source not found and no default driver specified’)

The drivers are installed in the data source (ODBC).
I tried different drivers, the error is the same. I can’t figure out what’s missing.

import sys
import pypyodbc
try:
  conn = pypyodbc.connect ('Driver = {ODBC Driver 13 for SQL Server}; Server = NameServer; uid = sa; pwd ='
              'myPassword; Database = BaseName ')
except Exception:
  print ("Error")
  print (sys.exc_info () [2])
else:
  print ("Connection")
  conn.close ()

This is what the DNS window looks like. Where do I need to add Drivers? Into user or system?

I added a driver. The error remains.

Made through pymssql. The code is working and connected to the database.

import pymssql
conn = pymssql.connect (server = 'serv', user = 'sa', password = 'PWD', database = 'DBname')
cursor = conn.cursor ()
cursor.execute ("SELECT IM FROM BID")
row = cursor.fetchone ()
for a in row:
  print (a)
conn.close ()

But still I want to understand why it does not work through pypyodbc. The point is clearly in the driver.
Maybe there are some nuances when adding to DNS? Or maybe Python doesn’t support all drivers? Or am I using the wrong connection string?


Answer 1, authority 100%

Try it with SQLAlchemy:

from sqlalchemy import create_engine
con = create_engine ('mssql + pymssql: // login: password @ server / base')

Answer 2, authority 100%

Must be created in the control panel – & gt; ODBC 32 / 64bit Data Sources – & gt; system DSN with the required parameters.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions