Reputation: 23
Im trying to insert all lines from a txt file, in the format name:age seperately into the database.
This is what I have tried:
with open('test.txt') as f:
reader = csv.reader(f)
for row in reader:
mycursor.execute("INSERT INTO test (name, age) VALUES (%s, %s)")
Txt file:
Adam:23
Olivia:19
Mark:45
Robert:34
Markus:23
Please help me to figure this out, or at least give me a hint, Im new to programming.
Upvotes: 2
Views: 731
Reputation: 18466
Your code is fine, you just need to insert the value tuple
in the query.
mycursor.execute("INSERT INTO test (name, age) VALUES (%s, %s)" %tuple(row.split(':'))
Or,
it will be even better if you separate your query from the data
query = "INSERT INTO test (name, age) VALUES (%s, %s)"
with open('test.txt') as f:
reader = csv.reader(f)
for row in reader:
mycursor.execute(query, %tuple(row.split(':'))
Upvotes: 0
Reputation: 26
agefile = open("text.txt", "r")
sql = "INSERT INTO test (nick, ip) VALUES (%s, %s)"
for row in agefile:
data = row.split(':')
val = (data[0], data[1])
mycursor.execute(sql, val)
agefile.close()
Upvotes: 1