How to Insert Data into Table using Python and MySQL
In this article, we will learn how to insert data into a table using MySQL Connector.
To insert new rows into a MySQL table, you have to follow these basic steps:
First connect to the MySQL database server by creating a new MySQLConnection
object. Then initiate a MySQLCursor
object from the MySQLConnection
object. Execute the INSERT
statement to insert data into the table. And finally close the database connection.
Insert one row into a table
from mysql.connector import MySQLConnection from python_mysql_dbconfig import read_db_config def insert_student(name, class): query = "INSERT INTO students(name, class) " \ "VALUES(%s,%s)" args = (name, class) db_config = read_db_config() conn = MySQLConnection(**db_config) cursor = conn.cursor() cursor.execute(query, args) if cursor.lastrowid: print('last insert id', cursor.lastrowid) else: print('last insert id not found') conn.commit() cursor.close() conn.close() def main(): insert_student('Dev','Class 10') if __name__ == '__main__': main()
Subscribe
Login
Please login to comment
0 Discussion