0

i am very new to mysql. i have to insert some data into the mysql table which i have already created. i have written a script to get two data and i need to insert that two data inside the 2 column of mysql table.

mysql database name is = Test1 table name is = all_data column name where i have to put value of "q" in column "query" and the value of "cnt_nas" in the column name "non_as_count" Below is my code:

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()

need some help.

s_m
  • 83
  • 1
  • 1
  • 9
  • possible duplicate of [How do I connect to a MySQL Database in Python?](http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python) – Harman Feb 12 '15 at 06:11
  • Try looking at this [SO question](http://stackoverflow.com/questions/5687718/how-can-i-insert-data-into-a-mysql-database) as well – Harman Feb 12 '15 at 06:13
  • @Harman i rewrite the code. will it work or not?? – s_m Feb 12 '15 at 06:24
  • Try rewriting it and if you're stuck somewhere, you can post the errors along with your findings – Harman Feb 12 '15 at 06:28
  • @Harman File "test.py", line 36, in db = MySQLdb.connect("localhost","root","******","Test1") File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect return Connection(*args, **kwargs) – s_m Feb 12 '15 at 06:50
  • super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") – s_m Feb 12 '15 at 06:51
  • @Harman i got the above ERROR – s_m Feb 12 '15 at 06:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/70779/discussion-between-harman-and-s-m). – Harman Feb 12 '15 at 10:49

0 Answers0