473,804 Members | 2,024 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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="localhos t", user="root", passwd="pw",
db="japanese")
cursor = connection.curs or()
cursor.execute( "INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s,
%s)", ("a", "b", "c") )
connection.clos e()

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 7168
grumfish wrote:
connection = MySQLdb.connect (host="localhos t", user="root", passwd="pw",
db="japanese")
cursor = connection.curs or()
cursor.execute( "INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s,
%s)", ("a", "b", "c") )
connection.clos e()


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.pytho n:
I'm trying to add a row to a MySQL table using insert. Here is the code:

connection = MySQLdb.connect (host="localhos t", user="root", passwd="pw",
db="japanese")
cursor = connection.curs or()
cursor.execute( "INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s,
%s)", ("a", "b", "c") )
connection.clos e()
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="tr3th4m k4r",
db="test",
host="localhost ")
cr = cn.cursor()

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

print res

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

res = cr.execute("sel ect * 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>pytho n 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.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.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="localhos t", user="root", passwd="pw",
db="japanese")
cursor = connection.curs or()
cursor.execute( "INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s,
%s)", ("a", "b", "c") )
connection.clos e()


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

Try this, instead:

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

connection.auto commit(True) # <--- note this
cursor = connection.curs or()

....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.auto commit) 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_fi le 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.pytho n
To: <py*********@py thon.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="localhos t", user="root", passwd="pw",
db="japanese")
cursor = connection.curs or()
cursor.execute( "INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s,
%s)", ("a", "b", "c") )
connection.clos e()

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************ *************** **********@pyth on.org>, 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

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

Similar topics

2
2099
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 MySQL sees this as 0000-00-00 instead of the date 2002-11-01. Other problem is the textstring in $_POST, in MySQL this stays empty. Can anybody help me with these problems, what am I doing wrong ?
3
2008
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 insert multiple and seperate strings (like an array or a csv file) inside of one row "cell" in a MySQL table. for examlpe id like to insert "review1..., review2..., review3..., review4..." inside a row "cell". id also like to be able to do a loop on them so i can format each string. is it possible...
2
5074
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 MySQL sees this as 0000-00-00 instead of the date 2002-11-01. Other problem is the textstring in $_POST, in MySQL this stays empty. Can anybody help me with these problems, what am I ding wrong ?
2
4892
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 trying to add the ability to delete rows if you check the checkbox in the cooresponding field and click remove item. I would appreciate any insite. BTW Am using IE browsers only. Thanks!
4
8609
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)? I’m new to this, so here’s what I’ve tried so far (unsuccessfully): 1. Fill Dataset ‘S’ from a SQL Data Adapter (many rows). I see it in a DataGrid. 2. Fill Dataset ‘A’ from an Access OLE DB Data Adapter (just a few rows). In a second DataGrid. 3. Merge dataset ‘S’...
5
2826
by: Stephen Preston | last post by:
Trying to load an multidimensional array into a MySQL table with columns as follows, level1,level2,level3,illust,item,description,partNo,qua,price,remarks,weight ,size,mass the array first line is $inputEngine the array secondline is $inputCylinder Head etc..
12
4451
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 as data in an INSERT to add a record to a mysql table. Then read the second line in text file and repeat. Thanks for your time Ian
3
745
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 then i want to insert 500 records at once,, as i explained below. here i declare 2 arrays of char and int to store the values i want,
3
1739
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 matter how I tweak the code, I always end up with "Error, insert query failed"... The code is: <h3><?php echo $_SESSION," ",$query; ?></h3> <?php $link = mysql_connect('localhost','root','EC4SPvRn');
0
9591
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10331
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10087
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9166
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7631
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6861
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.