我正在尝试连接到数据库并获取数据。
但是当我尝试写入文件时,它给了我以下错误。
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示例
book_id= cursor.fetchall() #List of rows
file_write.write(book_id) # you will get error `TypeError: expected a character buffer object`
file_write.write(', '.join(book_id))