Мой код:
import MySQLdb
def insert_popularity(PersonNumber, Category, Value):
# make a connection to the dataabse
connection = MySQLdb.connect(host='localhost', user='root', \
passwd='password', db='inb104')
# get a cursor on the database
cursor = connection.cursor()
# construct the SQL statement
sql = ("""INSERT INTO popularity (PersonNumber, Category, Value)
VALUES(%s, %s, %s)""", (number, category, data))
def open_file(filename):
txt_file = file(filename, 'r')
for line in txt_file:
# Split the line on whitespace
for value in line.split():
return value
number = value[0]
data = value[1]
# execute the query
cursor.execute(sql)
# commit the changes to the database\
connection.commit()
# close the cursor and connection
cursor.close()
connection.close()
Обновление:
После изменения моего кода согласно предложению Пауло Теперь я получаю эту ошибку:
query() argument 1 must be string or read-only buffer, not tuple.
Я не уверен, что это после попытки изменить мой код:
def insert_popularity(Category, filename, cursor):
txt_file = file(filename, 'r')
for line in txt_file:
# Split the line on whitespace
number, value = line.split()
# construct the SQL statement
sql = ("""INSERT INTO popularity (PersonNumber, Category, Value)
VALUES(%s, %s, %s)""", (number, Category, value))
# execute the query
cursor.execute(sql)
connection = MySQLdb.connect(host='localhost', user='root', \
passwd='password', db='dogs')
cursor = connection.cursor()
Category = 'dogs'
insert_popularity(Category, 'dogs.txt', cursor)
connection.commit()
cursor.close()
connection.close()