473,562 Members | 3,105 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 2496
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
1649
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...
5
1546
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
1030
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 ('测试')")...
1
5806
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
3649
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...
2
1585
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
4072
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
5423
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
7648
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, well explore What is ONU, What Is Router, ONU & Routers main...
0
7863
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. ...
0
8091
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...
1
7620
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...
0
6213
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 projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5473
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...
0
5189
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...
0
3618
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3602
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.