insert data to a table in mysql database

I was a bigginer so I asked this funny Question But for bigginers this is the answer:

make a connection:

conn = mysql.connector.connect (host = 'localhost', database = 'databasename', user = 'username', password = 'password')
cursor = conn.cursor()

make sure that you have table in database:

table_creation = """CREATE TABLE IF NOT EXISTS table_name (value_name1 value_type1, value_name2 value_type2, value_name3 value_type3)"""
cursor.execute (table_creation)
conn.commit()
cursor = conn.cursor()

then make insert text for table:

sql = """INSERT INTO table_name (value_name1, value_name2, value_name3) VALUES (%s, %s, %s)"""

put the values that can be a string, numeric, int, bool, date or name of variable with any data type and send them to table:

val = (value1, value2, value3)
cursor.execute(sql, val)
conn.commit()
cursor = conn.cursor()

then close your connection:

cursor.close()

thats all and very simple, for more information check the document of mysql.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top