[Tutor] MySQLdb: at a complete loss

Tiago Saboga tiagosaboga at terra.com.br
Sat Feb 18 23:29:33 CET 2006


Em Sáb 18 Fev 2006 17:51, Danny Yoo escreveu:
> > db=MySQLdb.connect(host='localhost',user='root',passwd='081300',db='tut')
> >     cursor=db.cursor()
> >     name = raw_input("Please enter a Name: ")
> >     color =raw_input("Please enter a Color: ")
> >     cursor.execute("""INSERT INTO horses(name,color)
> > VALUES("%s","%s")"""%(name,color))
>
>          ^^^^^^^^^
>
> Hi Servando,
>
> Don't do this: don't try to interpolate the variables yourself, but pass
> the parameters as part of the execution call:
>
>     http://mail.python.org/pipermail/tutor/2003-April/022010.html

It's interesting, but I'm missing something. What does it mean, a "prepared 
statement"? I can see *why" to use it, but not *what* it is. But wait... is 
it simply a difference between concatenating variables and putting them 
"inline" in the string? So the on the second line of code below mysql will 
know for sure that c is the wanted value for xname, even if it is something 
that should be quoted?

a="select xname,sname from people where xname='"+c+"'"

cursor.execute("select xname,sname from people where xname=%s", c)


> > this script runs without error and does not affect the database in any
> > manner.  The database does exist. User/Password are valid. I have run
> > the above script , unchanged, on both Macintosh and Ubuntu with success.
>
> Are you familiar with database transactions?  Look at the description of
> close() in the Python DB API:
>
>     """Close the connection now (rather than whenever __del__ is
>        called)...  Note that closing a connection without
>        committing the changes first will cause an implicit
>        rollback to be performed."""
>
>     (http://www.python.org/peps/pep-0249.html)
>
> Does this last sentence ring some bells?  *grin*
>
> Newest versions of the MySQLdb module do NOT autocommit anymore. You have
> to commit at the end or else you're not going to see any mutation affect
> the database: every change you make will just roll back.

Even with MyIsam tables, which are not transactional?

Tiago.


More information about the Tutor mailing list