Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

python - Retrieving SQL Server data using pyodbc is returning unexpected data values

I am learning Python and have written some code to retrieve data from a SQL Server table. The code is as follows:

import pyodbc

connection = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=xxx"
"Database=xxx"
"uid=xxx"
"pwd=xxx"
)

cursor = connection.cursor()
cursor.execute('SELECT * FROM Dealers')

for row in cursor:
print(list(row))

This code works fine but the output, for some data types isn't what I expected. For example, I have a line of output that looks like this:

Decimal('0.000'), Decimal('83.360'), True, True, Decimal('0.000'), datetime.date(2017, 5, 31), True, 1, True, True, datetime.datetime(2017, 5, 31, 18, 28, 57, 686666)

Instead of something like Decimal('83.360'), how do I simply get 83.360? Same for the date/time values?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Decimal('83.360') and datetime.date(2017, 5, 31) are the default representations (repr()) of a Decimal object and a datetime.date object. If you want "just 83.360 and 2017-05-31" then you can call str() on them (as opposed to repr()) and you will get a string representation of the value. Note however that

x = str(Decimal('83.360'))

will result in x being a str, i.e., it will have lost its number-ness, so

y = x + 1

results in an error ('TypeError: can only concatenate str (not "int") to str'), not 84.360.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...