Python stores dictionary content into mysql_MySQL

Source: Internet
Author: User
Python stores dictionary content into mysql python

1. the background project needs to use python to store dictionary content to a local mysql database. For example, a dictionary dic = {"a": "B", "c": "d"} is saved to the database as follows:
2. code
'''Insert items into database @ author: hakuri ''' import MySQLdbdef InsertData (TableName, dic): try: conn = MySQLdb. connect (host = 'localhost', user = 'root', passwd = '*****', db = 'test', port = 3306) # connect to database cur = conn. cursor () COLstr = ''# column field ROWstr ='' # row field ColumnStyle = 'varchar (20) 'for key in dic. keys (): COLstr = COLstr + ''+ key + ColumnStyle + ', 'rowstr = (ROWstr +'" % s "'+ ',') % (dic [key]) # check whether the table exists. if try exists, execute try. if try exists, execute begin T to create a new table, and then insert try: cur.exe cute ("SELECT * FROM % s" % (TableName) cur.exe cute ("insert into % s VALUES (% s)" % (TableName, ROWstr [: -1]) except MySQLdb. error, e: cur.exe cute ("create table % s (% s)" % (TableName, COLstr [:-1]) cur.exe cute ("insert into % s VALUES (% s)" % (TableName, ROWstr [:-1]) conn. commit () cur. close () conn. close () distinct T MySQLdb. error, e: print "Mysql Error % d: % s" % (e. args [0], e. args [1]) if _ name __= = '_ main _': dic = {"a": "B", "c ": "d"} InsertData ('testtable', dic)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.