Python caches dictionary contents in MySQL

Source: Internet
Author: User

1. BackgroundThe project needs to use Python to save the dictionary contents to the local MySQL database. For example, there is a dictionary dic={"a": "B", "C": "D"}, stored in the database as follows:
2. Code  
' Insert items into Database@author:hakuri ' ' Import mysqldbdef insertdata (tablename,dic): Try:conn=mysqldb.conn ECT (host= ' localhost ', user= ' root ', passwd= ' * * * *, db= ' test ', port=3306) #链接数据库 cur=conn.cursor () colstr= ' #列的字段 R             Owstr= ' #行字段 columnstyle= ' VARCHAR ' for key in Dic.keys (): colstr=colstr+ ' +key+columnstyle+ ', ' Rowstr= (rowstr+ ' "%s" ' + ', ')% (Dic[key]) #判断表是否存在, there is a execute try, there is no execution except new table, and then insert Try:cur.execute ("Sele CT * from%s "% (TableName)) Cur.execute (" INSERT into%s VALUES (%s) "% (tablename,rowstr[:-1)) except MySQLdb . Error,e:cur.execute ("CREATE TABLE%s (%s)"% (Tablename,colstr[:-1])) Cur.execute ("INSERT into%s VA Lues (%s) "% (Tablename,rowstr[:-1])) Conn.commit () Cur.close () conn.close () except Mysqldb.error,e:print" Mysql Error%d:%s "% (E.args[0], e.args[1]) if __name__== ' __main__ ': dic={" a ":" B "," C ":" D "} insertdata (' Testt       Able ', DIC)

Related Article

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.