- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to insert a Python object in MySQL?
Assuming that a MySQL database named 'test' is present on the server and a table named employee is also created. Let the table have five fields fname, lname, age, gender, and salary.
Suppose we want to insert a tuple object containing data of a record defined as follows into the Msql database.
t1=('Steven', 'Assange', 21, 'M', 2001)
To establish an interface between MySQL and Python 3, you need to install the PyMySQL module. Then you can set up the connection using the following statements
import PyMySQL # Open database connection db = PyMySQL.connect("localhost","root","","test" ) # prepare a cursor object using cursor() method cursor = db.cursor()
Next step is to set up the insert query using data in the tuple
sql="insert into employee values(%s,%s,%d,%s,%d)" %t1
Now this query is executed using execute() method of the cursor object
If you check the contents of the employee table, it will show a new record added to it.
- How to insert date object in MySQL using Python?
- How to insert a Python object in Mongodb?
- How to insert a Python tuple in a MySQL database?
- How to insert an object in a list at a given position in Python?
- How to form a MySQL Conditional Insert?
- How to do a batch insert in MySQL?
- How to insert a row into a ResultSet object using JDBC?
- How to insert a DATALINK object into a table using JDBC?
- How to multiple insert or batch insert at a time in MySQL query?
- How to insert an array of values in a MySQL table with a single INSERT?
- How to prevent duplicate INSERT in MySQL?
- How to easily insert datetime in MySQL?
- How to add a where clause in a MySQL Insert statement?
- How to insert a Python tuple in a PostgreSql database?
- How to insert current date/time in MySQL?