Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Python namedtuples to insert rows into mySQL database

I have used namedtuples to read rows from mySQL ... it is great. Can I use the same mechanism to INSERT rows into mySQL. My system is changing quite a bit, so I need an simple way to map python values to columns in the database, without having to check the order of the values/columns every time I change my program I am using mySQLDB library - but could change

like image 886
Bernard Avatar asked Nov 29 '25 17:11

Bernard


1 Answers

namedtuple for INSERT queries will behave just like normal tuples, you have to maintain the order of column/values. You can use named placeholders and dicts to avoid that.

cursor.execute("INSERT INTO person (name, age) VALUES (%(name)s, %(age)s)", {"name": "Bernard", "age": 30})

Related question: Python MySQLdb: Query parameters as a named dictionary

like image 56
Imran Avatar answered Dec 01 '25 05:12

Imran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!