TypeError:必须是字符串或只读字符缓冲区,而不是列表

时间:2014-11-27 12:48:10

标签: python database pyodbc

我正在尝试连接数据库并获取数据。

但是当我尝试写入文件时,它会给我以下错误。

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

请指导。

感谢。

2 个答案:

答案 0 :(得分:3)

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 example

答案 1 :(得分:1)

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))