473,787 Members | 2,928 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem With Insert with MySQLdb

Hello,

I am a complete beginner with Python. I've managed to get mod_python up and
running with Apache2 and I'm trying to a simple insert into a table in a
MySQL database.

I'm using the MySQLdb library for connectivity. I can read from the database
no problem, but when I do an insert, the value never gets added to the
database, even though there is no error, and the SQL is fine (I print out
the SQL statement in the function). When I copy and paste the sql from my
browser and insert directly into MySQL, it works fine.

Here is the function in question:

def add(req):
db = MySQLdb.connect (host="intranet ", user="root", passwd="",
db="intranet")
# create a cursor
cursor = db.cursor()
# execute SQL statement

sql = "INSERT INTO category (category_name) VALUES ('" +
req.form['category'] + "')"
cursor.execute( sql)
return sql
The SQL it is outputting is:

INSERT INTO category (category_name) VALUES ('Test')

Am I doing something obviously incorrect here?

Thanks,

Dave

Oct 30 '05 #1
3 2505
On Sun, 30 Oct 2005 18:44:32 -0500, "David Mitchell" <da**@dbmdata.c om>
declaimed the following in comp.lang.pytho n:

sql = "INSERT INTO category (category_name) VALUES ('" +
req.form['category'] + "')"
cursor.execute( sql)
Don't do that!

Use the execute() method to do parameter substitution...

sql = "insert into category (category_name) values (%s)"
res = cursor.execute( sql, (req.form["category"],) )

Then see what "res" contains.

Am I doing something obviously incorrect here?
The other possibility might be that the Apache/mod_python session is
running as a host/user that may not have update privileges on the MySQL
server.

-- =============== =============== =============== =============== == <
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/> <

Oct 31 '05 #2
David Mitchell wrote:
Hello,

I am a complete beginner with Python. I've managed to get mod_python up and
running with Apache2 and I'm trying to a simple insert into a table in a
MySQL database.

I'm using the MySQLdb library for connectivity. I can read from the database
no problem, but when I do an insert, the value never gets added to the
database, even though there is no error, and the SQL is fine (I print out
the SQL statement in the function). When I copy and paste the sql from my
browser and insert directly into MySQL, it works fine.

Here is the function in question:

def add(req):
db = MySQLdb.connect (host="intranet ", user="root", passwd="",
db="intranet")
# create a cursor
cursor = db.cursor()
# execute SQL statement

sql = "INSERT INTO category (category_name) VALUES ('" +
req.form['category'] + "')"
cursor.execute( sql)
return sql
The SQL it is outputting is:

INSERT INTO category (category_name) VALUES ('Test')

Am I doing something obviously incorrect here?

Thanks,

Dave


Try either executing this first:
cursor.execute( "set autocommit = 1")
or this afterwards:
cursor.execute( "commit")

The idea is that transactions are not committed into the database
until you "commit" them - and if you hit problems halfway through
a sequence of updates that really shouldn't be left half
finished, you can execute "abort" instead (or just close the
connection), and none of them will be done.

Steve
Oct 31 '05 #3
Dennis Lee Bieber wrote:
On Sun, 30 Oct 2005 18:44:32 -0500, "David Mitchell" <da**@dbmdata.c om>
declaimed the following in comp.lang.pytho n:
sql = "INSERT INTO category (category_name) VALUES ('" +
req.form['category'] + "')"
cursor.execute( sql)


Don't do that!

Use the execute() method to do parameter substitution...


This advice is really extremely important from a security
point of view if this is a web app. Pasting in data from
a web form into a SQL command like this is really asking
for trouble.

I this case, someone could for instance craft a http request
so that req.form['category'] contains:

"');DELETE FROM category;INSERT INTO category (category_name)
VALUES ('SUCKER!!!"

This SQL injection attack won't work if the SQL statement and
parameters are sent separately to the database server. (You
can't be sure that this is actually what happens just because
the Python DB-API looks like that though. Please verify that
your database driver is sane.)

Besides security, there are also performance issues here.
I'm not sure about MySQL, but most RDBMSs are much better if
it gets the same query many times, with different parameters
on each call, than if it gets many different queries, which
is what happens if you manually paste the parameter values
into the SQL string.

It's also a good idea to try to understand how transactions
work in SQL, and exactly when to do commit. In many cases,
using autocommit might lead to logically corrupt databases.

Some info can be found at: http://www.thinkware.se/epc2004db/
Nov 1 '05 #4

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

Similar topics

5
1660
by: Phillip | last post by:
Hi. I hate the way one has to jump through countless hoops to put data in a db and get it out again. The straightforward MySQLdb Interface requireing this SQL stuff being a point in case (against SQL and those RDBs that is). Since other programms have to access this data I'm forced to use a classical DB and actually have managed to set up Mysql and a presumably working connection from Python to it. I've gotten so far as to avoid errors...
5
1550
by: Lad | last post by:
I have the following program( only insert a record) ################ import MySQLdb conn = MySQLdb.connect (host = "localhost",user = "", passwd = "",db="dilynamobily") cursor = conn.cursor () cursor.execute("""CREATE TABLE produkt1 ( id int(10) unsigned NOT NULL auto_increment, MyNumber varchar(30) NOT NULL default '',
0
1036
by: liupei | last post by:
I am use mod_python3.2.8,MySQL-python-1.2.1_p2,mysql5.0.20,centOS when I run the script below(I have also saved this script in utf-8): #coding: utf-8 from MySQLdb import connect connection=connect(user='root',passwd='',host='localhost',db='test') cursor = connection.cursor() cursor.execute("INSERT INTO `fee` ( `affair` ) VALUES ('测试')") #'测试' is a chinese word means test it raise error:
1
5860
by: erikcw | last post by:
Hi, I'm trying to insert some data from an XML file into MySQL. However, while importing one of the files, I got this error: Traceback (most recent call last): File "wa.py", line 304, in ? main() File "wa.py", line 257, in main curHandler.walkData()
11
3668
by: krishnakant Mane | last post by:
hello, I finally got some code to push a pickled list into a database table. but now the problem is technically complex although possible to solve. the problem is that I can nicely pickle and store lists in a blob field with the help of dumps() for picklling into a string and then passing the string to the blob. I am also able to get back the string safely and do a loads() to unpickle the object. but this only works when list contains...
2
1596
by: hiroc13 | last post by:
>>import MySQLdb When I start this code I get ((15L, 'test', 1L),) on the screen but if I first execute this: ..... this write to table1 and now this:
2
4087
rhitam30111985
by: rhitam30111985 | last post by:
hi all .. consider the following code: i basically need to build a table in the mysql database with two fields , country and office list... import MySQLdb import sys import os os.system('clear') try: conn = MySQLdb.connect (host = "localhost",
5
5434
by: Florian Lindner | last post by:
Hello, I have a string: INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`, `gid`, `password`) VALUES (%s, %s, %s, %s, %i, %i, %s) that is passed to a MySQL cursor from MySQLdb: ret = cursor.execute(sql, paras)
0
457
by: Charles V. | last post by:
Hi, You are right: the default Cursor in MySQLdb fetches the complete set on the client (It explains why I have a "correct" answer with MySQLdb). As having multiple cursor isn't an option for me and using non-standard execute on the connection neither, I tried to modify the Cursor class to store results on the client side. ----------------
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9497
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
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9964
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...
1
7517
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
6749
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();...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.