0

I am trying to create a table in Python with MySQL, and then insert new values into the table!

The program works with no error message, but the table stays empty all the time. Here are my python scripts:

cursor = conn.cursor()
cursor.execute('DROP TABLE twitter')
cursor.execute("CREATE TABLE twitter (id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id CHAR, state CHAR(2), city CHAR, tweet CHAR, PRIMARY KEY (id))")

### after getting some data, then insert the data into the table: 
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})'.format(tw_userid, tw_state, tw_city, tw_text))
cursor.close()
conn.commit()
conn.close()

But any time I try to select data from this table, I get an empty set.

I also tried without using format option, but still I get an empty set:

cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})', (tw_userid, tw_state, tw_city, tw_text))

Any idea why the insert command doesn;t change the table at all?

1 Answer 1

1

You need to use a comma to separate parameters in python.

cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})'.format(tw_userid, tw_state, tw_city, tw_text))

Should be:

data = (tw_userid, tw_state, tw_city, tw_text)
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})', data)

You can see the documentation for the python connector on the mysql documentation page.

Sign up to request clarification or add additional context in comments.

2 Comments

I made that change, but still I get empty table!
@VahidMir see my updated answer. You can read more about format() here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.