3

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

Bernard
  • 63
  • 9

1 Answers1

3

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

Community
  • 1
  • 1
Imran
  • 87,203
  • 23
  • 98
  • 131