472,331 Members | 1,686 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,331 software developers and data experts.

Can't seem to insert rows into a MySQL table

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.
Jul 18 '05 #1
11 6964
grumfish wrote:
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
Jul 18 '05 #2
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.
Jul 18 '05 #3
On Sat, 12 Mar 2005 18:24:10 GMT, grumfish <no****@nowhere.com>
declaimed the following in comp.lang.python:
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>
-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #4
grumfish wrote:
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.

--
"Per bello sapere che, di questi tempi spietati, almeno
un mistero sopravvive: l'et di Afef Jnifen." -- dagospia.com
Jul 18 '05 #5
Patrick Useldinger wrote:
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?
Jul 18 '05 #6
deelan wrote:
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. :)

--
"Per bello sapere che, di questi tempi spietati, almeno
un mistero sopravvive: l'et di Afef Jnifen." -- dagospia.com
Jul 18 '05 #7
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/ch...onnection.html

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

Jul 18 '05 #8
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" <no****@nowhere.com>
Newsgroups: comp.lang.python
To: <py*********@python.org>
Sent: Saturday, March 12, 2005 7:24 PM
Subject: Can't seem to insert rows into a MySQL table

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.
--
http://mail.python.org/mailman/listinfo/python-list


Jul 18 '05 #9
In <ma*************************************@python.or g>, Anthra Norell
wrote:
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
Jul 18 '05 #10
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" <bj****@gmx.net>
Newsgroups: comp.lang.python
To: <py*********@python.org>
Sent: Monday, March 14, 2005 11:55 PM
Subject: Re: Can't seem to insert rows into a MySQL table

In <mailman.410.1110836641.1799.py*********@python.or g>, Anthra Norell
wrote:
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
--
http://mail.python.org/mailman/listinfo/python-list


Jul 18 '05 #11
Anthra Norell wrote:
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().
In <ma*************************************@python.or g>, Anthra Norell wrote:
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") )


Don't do this.

Jul 18 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: edward hage | last post by:
Hello, I don't seem to get the following right. In the following I try to fill a MySQL table named 'mutation'. The first element is a date but...
3
by: kiqyou_vf | last post by:
im sort of a newbie to all of this and my terminology isnt accurate but i have a couple simple questions. ive been looking around for a way to...
2
by: edward hage | last post by:
Hello, I don't seem to get the following right. In the following I try to fill a MySQL table named 'mutation'. The first element is a date but...
2
by: Spanky | last post by:
Thanks for any help in advance! I have this order form where you add rows as you need them. The routine to add fields is working fine. I am...
4
by: RG | last post by:
Using VB.NET, How do I insert rows from a SQL Server table into an Access table with the same structure (and also the reverse, from Access to SQL)?...
5
by: Stephen Preston | last post by:
Trying to load an multidimensional array into a MySQL table with columns as follows, ...
12
by: mantrid | last post by:
Hello Can anyone point me in the right direction for the way to read a text file a line at a time and separate the fields on that line and use them...
3
by: Waruna | last post by:
Is there a way to block insert into mysql(5.0) using c api of mysql db.. i.e. say there is a table with 2 columns, one contains char other int...
3
by: hnmcc | last post by:
I don't know whether this belongs here or in the MySQL section. I'm trying to write a couple of values from a search page to a database: but no...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.