473,799 Members | 3,033 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

MySQL problem

Lad
I have the following
program( only insert a record)
############### #
import MySQLdb
conn = MySQLdb.connect (host = "localhost",use r = "", passwd =
"",db="dilynamo bily")
cursor = conn.cursor ()
cursor.execute( """CREATE TABLE produkt1 (
id int(10) unsigned NOT NULL auto_increment,
MyNumber varchar(30) NOT NULL default '',
PRIMARY KEY (id))
""")

#MyValue=111
cursor.execute ("""INSERT INTO produkt1
(MyNumber)
VALUES(111)
""")
############### ##
It works. But If I change the program like the following ( only use a
variable MyValue in INSERT statement it does not work.
##########THIS DOES NOT WORK########
import MySQLdb,re,stri ng
conn = MySQLdb.connect (host = "localhost",use r = "", passwd =
"",db="dilynamo bily")
cursor = conn.cursor ()
cursor.execute( """CREATE TABLE produkt1 (
id int(10) unsigned NOT NULL auto_increment,
MyNumber varchar(30) NOT NULL default '',
PRIMARY KEY (id))
""")

MyValue=111
cursor.execute ("""INSERT INTO produkt1
(MyNumber)
VALUES(MyValue)
""")
############### ##
Program says
OperationalErro r: (1054, "Unknown column 'MyValue' in 'field list'")
Where is a problem. Thanks for help
Lad.

Jul 18 '05 #1
5 1552
Lad wrote:
I have the following
program( only insert a record)
############### #
import MySQLdb
conn = MySQLdb.connect (host = "localhost",use r = "", passwd =
"",db="dilynamo bily")
cursor = conn.cursor ()
cursor.execute( """CREATE TABLE produkt1 (
id int(10) unsigned NOT NULL auto_increment,
MyNumber varchar(30) NOT NULL default '',
PRIMARY KEY (id))
""")

#MyValue=111
cursor.execute ("""INSERT INTO produkt1
(MyNumber)
VALUES(111)
""")
############### ##
It works. But If I change the program like the following ( only use a
variable MyValue in INSERT statement it does not work.
##########THIS DOES NOT WORK########
import MySQLdb,re,stri ng
conn = MySQLdb.connect (host = "localhost",use r = "", passwd =
"",db="dilynamo bily")
cursor = conn.cursor ()
cursor.execute( """CREATE TABLE produkt1 (
id int(10) unsigned NOT NULL auto_increment,
MyNumber varchar(30) NOT NULL default '',
PRIMARY KEY (id))
""")

MyValue=111
cursor.execute ("""INSERT INTO produkt1
(MyNumber)
VALUES(MyValue)
""")
############### ##
Program says
OperationalErro r: (1054, "Unknown column 'MyValue' in 'field list'")
Where is a problem. Thanks for help
Lad.


Lad,
Try

str = "INSERT INTO produkt1 (MyNumber) VALUES(%d)" % (MyNumber)
cursor.execute( str)

wes

Jul 18 '05 #2
On Thu, 17 Mar 2005 16:45:57 GMT, wes weston <ww*****@att.ne t> declaimed
the following in comp.lang.pytho n:

str = "INSERT INTO produkt1 (MyNumber) VALUES(%d)" % (MyNumber)
cursor.execute( str)
Think you meant "MyValue" for the second item... However...

Try neither, the recommended method is to let the execute() do
the formatting... That way /it/ can apply the needed quoting of
arguments based upon the type of the data.

cursor.execute( "insert into produkt1 (MyNumber) values (%d)", (MyValue))

-- =============== =============== =============== =============== == <
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 #3
Dennis Lee Bieber wrote:
On Thu, 17 Mar 2005 16:45:57 GMT, wes weston <ww*****@att.ne t> declaimed
the following in comp.lang.pytho n:

str = "INSERT INTO produkt1 (MyNumber) VALUES(%d)" % (MyNumber)
cursor.execut e(str)


Think you meant "MyValue" for the second item... However...

Try neither, the recommended method is to let the execute() do
the formatting... That way /it/ can apply the needed quoting of
arguments based upon the type of the data.

cursor.execute( "insert into produkt1 (MyNumber) values (%d)", (MyValue))


Dennis,
Do you know if this has some efficiency advantage
or is it just an agreed upon custom.
wes

Jul 18 '05 #4
wes weston wrote:
Dennis Lee Bieber wrote:
Try neither, the recommended method is to let the execute() do
the formatting... That way /it/ can apply the needed quoting of
arguments based upon the type of the data.

cursor.execute( "insert into produkt1 (MyNumber) values (%d)", (MyValue))


Dennis,
Do you know if this has some efficiency advantage
or is it just an agreed upon custom.


It may have efficiency advantages if the DB caches requests. But the main advantages are that
- it correctly escapes special chars such as "
- consequently it also protects against SQL injection attacks where MyValue might contain malicious SQL.

Kent
Jul 18 '05 #5
On Fri, 18 Mar 2005 16:22:37 GMT, wes weston <ww*****@att.ne t> declaimed
the following in comp.lang.pytho n:
Dennis Lee Bieber wrote:

cursor.execute( "insert into produkt1 (MyNumber) values (%d)", (MyValue)) I meant %s there, not %d
Dennis,
Do you know if this has some efficiency advantage
or is it just an agreed upon custom.


A more critical reason is the module itself can handle the
quoting and escaping needed for the odder data types. Consider what
happens if:

avalue = '''"This is a 'string' with both types of 'quotes'"'''
(that is 3*', ", 'x', 'x', ", 3*')

and you use the % operator on

sql = "insert into atable (afield) values (%s)" % avalue

<print sql>

insert into atable (afield) values ("This is a 'string' with both types
of 'quotes'")

The " are taken by MySQL as the delimiters of the string value, not part
of the string data.

But if you use:

sql = "insert into atable (afield) values ('%s')" % avalue

you get

insert into atable (afield) values ('"This is a 'string' with both types
of 'quotes'"')

Note that MySQL will complain at 'string, as the ' closes the string
"This is a

Letting .execute(templa te, (values)) do the substitution will generate
the proper (without, I believe, having to put quotes around the %s):

insert into atable (afield) values ('"This is a \'string\' with both
types of \'quotes\'"')

or, if .execute() defaults to using " instead of '

insert into atable (afield) values ("\"This is a 'string' with both
types of 'quotes'\"")
Their is also, as I recall, an .executemany() that some RDBMs
support. For these, you MUST let the module do the substitution:

c.executemany(t emplate,
((record1 values),
(record2 values), ...,
(record-n values)) )

-- =============== =============== =============== =============== == <
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 #6

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

Similar topics

0
6528
by: JL | last post by:
Platform: Linux Red Hat RHEL 3 (and red hat 9) Installed MySQL from source. As a matter of fact, installed all LAMPS from source, and the mysql socket file was arranged in a place other than /tmp/mysql.sock. Let's say, /opt/mysql_root/sock/mysql.sock. Installed DBI without any problem. In /etc/my.cnf there are lines as ----- ----- -----
0
3532
by: Lenz Grimmer | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, MySQL 4.0.14, a new version of the popular Open Source/Free Software Database, has been released. It is now available in source and binary form for a number of platforms from our download pages at http://www.mysql.com/downloads/ and mirror sites.
3
1645
by: Kirk Soodhalter | last post by:
Hi, This started as a phpmyadmin problem, but has somehow morphed into a mysql problem. I don't know how to fix it. I am posting the conversation from a php newsgroup since it started there. Thanks for any help you might be able to give. -Kirk Ok, in the midst of fixing this problem I have somehow managed to create
0
519
by: Plymouth Acclaim | last post by:
Hi guys, We have a problem with Dual AMD64 Opteron/MySQL 4.0.18/Mandrake 10 for a very high volume site. We are evaluating the performance on our new server AMD64 and it seems it's slow compared to Dual Xeon/MySQL 4.0.15/RedHat8 and Dual Xeon/MySQL 4.0.18/Mandrake 10. And it seems there are zombie threads. 570 threads in 1 hour and we didn't even use JDBC connection pooling at all. These threads are supposed to be gone within 60...
1
3827
by: Alex Hunsley | last post by:
I am trying to install the DBD::mysql perl module. However, it claims I need mysql.h: cpan> install DBD::mysql CPAN: Storable loaded ok Going to read /home/alex/.cpan/Metadata Database was generated on Mon, 29 Nov 2004 16:01:05 GMT Running install for module DBD::mysql Running make for R/RU/RUDY/DBD-mysql-2.9004.tar.gz CPAN: Digest::MD5 loaded ok
1
3644
by: smsabu2002 | last post by:
Hi, I am facing the build problem while installing the DBD-MySql perl module (ver 2.9008) using both GCC and CC compilers in HP-UX machine. For the Build using GCC, the compiler error is produced due to the unknown GCC compiler option "+DAportable". For the Build using CC, the preprocessor error is produced due to the recursive declration of macro "PerlIO" in perlio.h file.
1
4857
by: jrs_14618 | last post by:
Hello All, This post is essentially a reply a previous post/thread here on this mailing.database.myodbc group titled: MySQL 4.0, FULL-TEXT Indexing and Search Arabic Data, Unicode I was wondering if anybody has experienced the same issues
110
10633
by: alf | last post by:
Hi, is it possible that due to OS crash or mysql itself crash or some e.g. SCSI failure to lose all the data stored in the table (let's say million of 1KB rows). In other words what is the worst case scenario for MyISAM backend? Also is it possible to not to lose data but get them corrupted?
39
5873
by: alex | last post by:
I've converted a latin1 database I have to utf8. The process has been: # mysqldump -u root -p --default-character-set=latin1 -c --insert-ignore --skip-set-charset mydb mydb.sql # iconv -f ISO-8859-1 -t UTF-8 mydb.sql mydb_utf8.sql mysqlCREATE DATABASE mydb_utf8 CHARACTER SET utf8 COLLATE utf8_general_ci;
10
1825
by: Caffeneide | last post by:
I'm using a php script which performs three xml queries to other three servers to retrieve a set of ids and after I do a query to mysql of the kind SELECT * FROM table WHERE id IN ('set of ids'); Although I'm sure the connection to the database is ok, I sometimes get an error of this kind: *Warning*: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in ... This does not happen every time i run the script, only...
0
9544
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
10259
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
10238
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,...
1
7570
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
6809
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
5589
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4145
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
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
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.