使用python将数据插入mysql表

时间:2015-02-12 06:02:12

标签: python mysql

我是mysql的新手。我必须将一些数据插入到我已经创建的mysql表中。 我写了一个脚本来获取两个数据,我需要在mysql的2列中插入这两个数据 表

mysql数据库名称= Test1 表名是= all_data 列名,我必须把" q"的值在列"查询" 以及" cnt_nas"的价值在列名称" non_as_count" 以下是我的代码:

import collections
import MySQLdb
queries = ['shoes','memory card','earphones','led bulb','mobile','lunch box','helmets','sunglasses','blackberry','headphones']
queries_as = ['shoes','memory card','earphones','led bulb','mobile','earphones','led bulb','mobile']
queries_non_as = ['lunch box','helmets','sunglasses','blackberry','headphones','sunglasses','blackberry','headphones']
for q in queries:
   cnt_as = queries_as.count(q)
   cnt_nas = queries_non_as.count(q)
   ratio = (cnt_nas*100)/(cnt_as+cnt_nas)
   if ratio <= 40:
       print q,cnt_nas   # this two i need to insert
       db = MySQLdb.connect("localhost","root","*****","Test1")
       cursor = db.cursor()
       sql = "insert into all_data values(%s,%s)" ,(q,cnt_nas)
       cursor.execute(sql)
       db.commit()
       db.close()

需要一些帮助。

0 个答案:

没有答案