Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Create MySQL Database Login Page in Python using Tkinter
Next article icon

 Prerequisites:MySQL,mysql-connector for python

The task here is to draft a Python program that works with SQL support to connect data. Whenever insertion into the database takes place, the ID of the row inserted will be printed. To connect python with the database we are using MySQL connector. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and MySQL Server. 

INSERT Clause in SQL

As the name suggests, it inserts data into the database. Certain rules need to be followed while using the insert command. The data to be updated should either be in the same order as the columns of the database or names of the columns should be given to the query along with the data to be inserted.

Syntax:

INSERT INTO <tablename>(Col1,Col2, ...)

VALUES(....);

To print the ID of the last inserted rowlastrowidwill be used. This is a special keyword that prints the ID of the row last inserted but to do so there are certain protocols that had to be kept in mind before employing this:

  • ID column of the database should be a primary key
  • ID column should auto-incremented.

Given below is the implementation of the same:

Database In Use:

Below is the implementation:

Python3
importmysql.connectormydb=mysql.connector.connect(host='localhost',database='employee',user='root',password='Your_pass')cs=mydb.cursor()statement="INSERT INTO geekstudent( id, name,gender, subject)\VALUES(6,'Shoit','M', 'ML')"cs.execute(statement)mydb.commit()print(cs.rowcount," record(s) added")print(cs.lastrowid)

Output:

1  record(s) added0

Updated Database Output:


Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp