2

I am trying to iterate through each row in my database and edit a single column for each of them. The column is called "name" (a varchar) and it is in the company table.

I am trying to remove the commas and then update it in my database.

So far what I have is this:

cursor = db.cursor()

companynames = cursor.execute("SELECT name FROM company;")

for row in cursor:

    row.replace(",", "")

This does not work properly.

print row returns ('Syntel, Inc. ',) ... A tuple

What can I do to properly retrieve the varchar field and then update it? `

2 Answers 2

1

Mysql has a REPLACE function.

The most efficient way to do this would be:

cursor.execute("UPDATE company SET name = replace(name, ',', '')")
db.commit()

If you want to pull the rows into python and then edit the string, you can do so like this:

corrected_names = []
for row in cursor.execute('SELECT name FROM company'):
    corrected_names.append(row[0].replace(',', ''))

this puts all the corrected names in a new list.

however, this approach can still be improved upon.

corrected_rows = []
for row in cursor.execute('SELECT id, name FROM company'):
    corrected_rows.append((row[0], row[1].replace(',', '')))

Here we're querying the primary key, as well as the field we're interested in, and then adding the edited row to our list. So now corrected_rows is a list of tuples.

After we're done editing the fields as we please, we can update the some or all of the rows in the database because we have the primary key.

This method gives the greatest flexibility.

Sign up to request clarification or add additional context in comments.

1 Comment

You can wrap the replace function on itself multiple times (replace(replace(name, ',', ''), 'acne', 'acme') but that gets ugly quickly. instead, just execute multiple update statements and commit.
1

Haleemur's answer is the correct one for a MySQL only approach (which honestly is likely the best approach, but I don't know your needs).

As far as your python is concerned, row is just coming back with the tuple of your data. Since the only column you're selecting is in the first position, you can extract that string with index notation: row[0]. In your case:

removedCommas = row[0].replace(",", "")
# Do work with the string removedCommas

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.