MySQLdb Help
Ervin Hegedüs
airween at gmail.com
Tue Sep 17 04:41:26 EDT 2013
Hello,
On Tue, Sep 17, 2013 at 12:43:20PM +0530, Venkat Addala wrote:
> Hi all,
>
>
> I'm new to python, i am connecting mysql database with python. now i want
> to do sanitation on the database, like to remove "\n", extra spaces blah
> blah.. and update it back to mysql database. i was trying somthing, here is
> my code, can you please provide me solution for this..
>
> #!/usr/bin/python
> import MySQLdb as mdb
>
> con = mdb.connect('localhost', 'root', 'pass at 123', 'workbench');
a tip: you can pass the arguments to function as dictionary, so
if you store the connection arguments anywhere, you use this
form:
conndsc = {'host': 'localhost', 'user': 'root', 'port': 3306, ....}
con = mdb.connect(**conndsc)
My personal opinion, but it's easyer to use the cursor if you
have dictionary-like cursor:
> with con:
> cur = con.cursor()
cur = con.cursor(mdb.cursors.DictCursor)
In this case you can reference the name of the table column,
instead of index of result, in your example:
row['descrip']
> cur.execute("SELECT descrip FROM table LIMIT 1")
> rows = cur.fetchall()
if you want to fetch only one row, you can use cur.fetchrow(),
which gives only one row, and you don't need to iterate that
> for row in rows:
> row_new = row[0].split("\n", " ")
> row = "".join(row_new)
as Benn Finney wrote, the use of split() above is wrong.
I think you need some kinf of this:
" ".join([f.strip() for f in row[0].replace("\n", " ").split()])
but it depends what you want.
Cheers:
Ervin
More information about the Python-list
mailing list