Python到SQL Server的连接

时间:2016-07-11 12:54:05

标签: python sql-server python-3.x pypyodbc

我正在使用带有Anaconda软件包2.4.0的Python 3.5.1并尝试连接到本地SQL Server(2008 R2)

接下来要做的事情:

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

在所有操作之后,收到错误:

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

为什么这样做以及我应该采取什么措施来避免它并正确运行连接?

1 个答案:

答案 0 :(得分:0)

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.