0
# -*- coding: utf-8 -*-

import re
import sys
import MySQLdb
from getpass import getpass

reload(sys)
sys.setdefaultencoding('utf-8')

conn = MySQLdb.connect(host, user, passwd, db, charset = 'utf-8')
cur = conn.cursor()
cur.execute("show tables")
tablenames = [i[0] for i in cur.fetchall()]

cur.execute("SELECT * FROM %s" % tablenames)
rows = cur.fetchall()
for row in rows:
    x = re.compile(r"\bhello\b")
    p = x.search(str(row))
    if p:
    cur.execute("DELETE FROM %s WHERE " % t) # how to delete this row

conn.close()

Using the code above, I would like to search the table rows with regular expressions, and search for the keyword "hello".

If it's matched, I'd like to delete the row which for loop in rows that fetched all.

How can I write the delete statement when the regular expression found the row?

Thanks very much!

2
  • That's not a row, it's a tablename (as indicated by your variable name) Do you want to DROP TABLE it or DELETE FROM all the rows in it, or something else? Commented Sep 20, 2012 at 16:46
  • that "where" line i'm not finished, i want to delete one row that fit my search condition, delete one row that i checking. Commented Sep 21, 2012 at 0:58

2 Answers 2

2

you can use LIKE in your SQL:

DELETE FROM `table` WHERE `content` LIKE "%value%"

and important thing after executing your sql is commit:

a = cur.execute(sql)
con.commit()
Sign up to request clarification or add additional context in comments.

Comments

0

If as I suspect you want to delete rows which meet some criteria than you don't need the select at all.
DELETE FROM tableName WHERE columnName [=, !=, <, >, LIKE] columnValue
If you need regex match than read this: http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.