Python to SQL Server connection

Question:

I’m using Python 3.5.1 with Anaconda package 2.4.0 and try to make a connection to local SQL Server (2008 R2)

So doing the next things:

import pypyodbc
connection_string =pypyodbc.connect('Driver={SQL Server};Server=PCMSSQLSERVER,1433;Database=localbase;Uid=name;Pwd=pass')
connection_string=connection_string.decode(encodind='utf-8',errors='replace')

After all the manipulations, receive the error:

'utf-32-le' codec can't decode bytes in position 0-1: truncated data

Why’s that and what should I perform to avoid it and run the connection properly?

Asked By: Keithx

||

Answers:

You seem to have misunderstood what a “connection string” is. It is the text string that you pass to the .connect method, not what is returned from the .connect method. (What gets returned is a connection object.)

So, you need to do something more like this:

import pypyodbc
connection_string = "DRIVER={SQL Server};SERVER= ...(and so on)..."
conn = pypyodbc.connect(connection_string)
crsr = conn.cursor()
crsr.execute("SELECT stuff FROM tablename")
# etc.
Answered By: Gord Thompson
import pymssql
conn = pymssql.connect(server='servername', user='username', 
password='password', database='databasename')
print("Connected to Database")

Use this string connection to connect do database 🙂

Answered By: traiz