Can't seem to insert rows into a MySQL table

G

grumfish

I'm trying to add a row to a MySQL table using insert. Here is the code:

connection = MySQLdb.connect(host="localhost", user="root", passwd="pw",
db="japanese")
cursor = connection.cursor()
cursor.execute("INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s,
%s)", ("a", "b", "c") )
connection.close()

After running, a SELECT * on the table shows no new rows added. Adding
rows using the MySQL client works fine. With the Python script, nothing.
There are no exceptions raised or any output at all. The rowcount of the
cursor is 1 after the execute is 1 and the table's auto_increment value
is increased for each insert done. Can anybody help? I'm fairly new to
MySQL so I'm afraid its going to be a stupid oversight on my part. Thank
you.
 
P

Patrick Useldinger

grumfish said:
connection = MySQLdb.connect(host="localhost", user="root", passwd="pw",
db="japanese")
cursor = connection.cursor()
cursor.execute("INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s,
%s)", ("a", "b", "c") )
connection.close()

Just a guess "in the dark" (I don't use MySQL): is "commit" implicit, or
do you have to add it yourself?

-pu
 
S

Stephen Prinster

grumfish wrote:
The rowcount of the
cursor is 1 after the execute is 1 and the table's auto_increment value
is increased for each insert done.

If the auto_increment is increased, then it seems like the row was
inserted. Are you sure the problem is not with your SELECT attempt?
Just a guess, but it seems like the first time I used MySQLdb, I was
confused by the need to do a "fetchall()" (or "fetchone()" or
"fetchmany()") after executing the SELECT.

Something like this (not tested):

result = cursor.execute(SELECT * FROM edict WHERE kanji = 'a')
print result.fetchall()

HTH,
Steve P.
 
D

Dennis Lee Bieber

I'm trying to add a row to a MySQL table using insert. Here is the code:

connection = MySQLdb.connect(host="localhost", user="root", passwd="pw",
db="japanese")
cursor = connection.cursor()
cursor.execute("INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s,
%s)", ("a", "b", "c") )
connection.close()
What is the definition of the table in use? Unique indices, etc.

My test, using the following test table definition:

mysql> show columns from edict;
+---------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+----------------+
| kanji | char(50) | | | | |
| kana | char(50) | | | | |
| meaning | char(50) | | | | |
| ID | int(10) unsigned | | PRI | NULL | auto_increment |
+---------+------------------+------+-----+---------+----------------+
4 rows in set (0.17 sec)

and this code:

-=-=-=-=-=-=-=-=-
import MySQLdb

cn = MySQLdb.connect(user="wulfraed",
passwd="tr3th4mk4r",
db="test",
host="localhost")
cr = cn.cursor()

res = cr.execute("insert into edict(kanji, kana, meaning) values (%s,
%s, %s)",
("a", "b", "c"))

print res

##cr.close()
##
##cr = cn.cursor()

res = cr.execute("select * from edict")

print res

for rw in cr.fetchall():
print rw

cr.close()
cn.close()
-=-=-=-=-=-=-=-

gives the following (it keeps adding a row each time I run)

G:\My Documents>python t.py
1
5
('a', 'b', 'c', 1L)
('a', 'b', 'c', 2L)
('a', 'b', 'c', 3L)
('a', 'b', 'c', 4L)
('a', 'b', 'c', 5L)

G:\My Documents>


--
 
G

grumfish

Patrick said:
Just a guess "in the dark" (I don't use MySQL): is "commit" implicit, or
do you have to add it yourself?

Thank you. Inserts work fine now.

Another question. I'm trying to insert Japanese text into the table. I
created the database using 'CHARACTER SET UTF8'. In Python I do a
..encode("utf-8") on any strings before inserting them into the database.
When I try to read them back from the database I don't get the original
string. I've played with .decode("utf-8") on strings returned from MySQL
but with no luck. How can I insert Japanese text into a MySQL database
and the read it out again?
 
D

deelan

grumfish said:
I'm trying to add a row to a MySQL table using insert. Here is the code:

connection = MySQLdb.connect(host="localhost", user="root", passwd="pw",
db="japanese")
cursor = connection.cursor()
cursor.execute("INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s,
%s)", ("a", "b", "c") )
connection.close()

which version of MySQLdb are you running? versions
1.1.6 and below gained a connection.autocommit) method set by default
to *false*.

Try this, instead:

connection = MySQLdb.connect(host="localhost", user="root", passwd="pw",
db="japanese")

connection.autocommit(True) # <--- note this
cursor = connection.cursor()

....other commands...

doing this you tell MySQL to automatically commit changes to db after
every UPDATE or INSERT. turning autocommit to false is useful when
you wish to do changes in batches and maybe rollback the entire operation
if something went wrong (see commit() and rollback() methods for this).

hope this helps,
deelan.
 
D

deelan

deelan said:
which version of MySQLdb are you running? versions
1.1.6 and below gained a connection.autocommit) method set by default
ehm, 1.1.6 and *above*, of course. :)
 
A

Andy Dustman

The default character set used by MySQL for the connection is latin1.
If you control the server, you can configure this in the system my.cnf.
Otherwise, it is possible to set it in a local configuration file and
use the read_default_file option to connect to set it.

http://dev.mysql.com/doc/mysql/en/charset-connection.html

I think setting the default to utf-8 on the server is your best bet, if
you are able to.
 
A

Anthra Norell

Try to use % instead of a comma (a Python quirk) and quotes around your
strings (a MySQL quirk):

cursor.execute("INSERT INTO edict (kanji, kana, meaning) VALUES ('%s',
'%s', '%s')" % ("a", "b", "c") )

Frederic


----- Original Message -----
From: "grumfish" <[email protected]>
Newsgroups: comp.lang.python
To: <[email protected]>
Sent: Saturday, March 12, 2005 7:24 PM
Subject: Can't seem to insert rows into a MySQL table
 
M

Marc 'BlackJack' Rintsch

Anthra Norell said:
Try to use % instead of a comma (a Python quirk) and quotes around your
strings (a MySQL quirk):

cursor.execute("INSERT INTO edict (kanji, kana, meaning) VALUES ('%s',
'%s', '%s')" % ("a", "b", "c") )

AFAIK grumfish made the Right Thingâ„¢. If you use '%', some interesting
things can happen, e.g. if your values contain "'" characters. The "%s"s
without quotes and the comma let the DB module format and *escape* the
inserted values for you in a safe way.

Ciao,
Marc 'BlackJack' Rintsch
 
A

Anthra Norell

Very true!
I could verify that cursor.execute () seems to understand "... %s ...",
...."string"... where print () doesn't.. I didn't know that.
I could also verify that gumfish's ineffective insertion command works fine
for me. (Python 2.4, mysql-3.23.38). So it looks like the problem is with
MySQL (e.g. table name, column names, ...)
Frederic

----- Original Message -----
From: "Marc 'BlackJack' Rintsch" <[email protected]>
Newsgroups: comp.lang.python
To: <[email protected]>
Sent: Monday, March 14, 2005 11:55 PM
Subject: Re: Can't seem to insert rows into a MySQL table
 
A

Andy Dustman

Anthra said:
Very true!
I could verify that cursor.execute () seems to understand "... %s ....",
..."string"... where print () doesn't.. I didn't know that.
I could also verify that gumfish's ineffective insertion command works fine
for me. (Python 2.4, mysql-3.23.38). So it looks like the problem is with
MySQL (e.g. table name, column names, ...)

I'm not sure if this is what you are referring to, but here's the
definitive answer:

MySQLdb uses %s as a parameter placeholder. When you pass the
parameters in a tuple as the second argument (as PEP-249 and the API
documentation tells you to), MySQLdb escapes any special characters
that may be present, and adds quotation marks as required.

However, the only parameters you can pass in that way are SQL literal
values, i.e. 15, 'string literal', '2005-03-15', etc. You can NOT pass
in things like names (column, table, database) or other pieces of
arbitrary SQL; these would be treated as strings, and thus be quoted.

Anything other than literal values has to be added some other way,
either by use of format strings and % or string concatenation, or
whatnot. You can double the % (i.e. %%s) so that if you also have
parameters to pass, their placeholder will be preserved.

You need to be very careful about what you allow to be inserted into
your SQL query when not using the quoting/escaping of execute().

Don't do this.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top