我正在尝试连接到数据库并获取数据。
但是,当我尝试写入文件时,出现以下错误。
TypeError: must be string or read-only character buffer, not list
下面是我的示例代码。
import pyodbc
path= "M:/xyz/"
file_write=open( path +"files.test.log", "w")
#print "Connection started"
db=pyodbc.connect('DSN=DB_NAME;PWD=xyz')
#print "Connection done"
cursor = db.cursor()
book_value="WPZ.N"
query="SELECT book_id FROM Table_name WHERE book_value='"+book_value+"'"
#print query
cursor.execute(query)
book_id= cursor.fetchall()
file_write.write(book_id)
#str(file_write)
#print file_write
请对此进行指导。
谢谢。
fetchall()
返回一个行列表,您应该从该列表中获取真正的具有字符串类型的'book_id'并将其写入文件。
试试这个:
rows = cursor.fetchall()
for row in rows:
file_write.write(row.book_id) # not sure if row[0] works as well
file_write.write('\n') # new line or anything else you like
来源:pyodbc示例
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句