473,809 Members | 2,699 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help formatting a mysql query string

Hi,

I am trung to create a mysql query string that contais two variables, the
first holds a table name and the second holds the values as a tuple. I
have tried the following however I can not work out how to get the format
right so the %s is subsituted with the contents of the variable, I think I
just have the quoting wrong, can anyone advise?

tablename contains the table I want to use
datavalue contains the data I want to use (contains multiple fields, we will
say 3 here for this example)

sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s )", datavalue"

Any help appreciated

Thanks

Rigga
Jul 18 '05 #1
3 5012
sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s )", datavalue"


- what are the "," doing here if you are trying to build a string ?
- you should use the python povided way which is better (yours looks like
php)

cursor.execute( "INSERT INTO %(tb)s VALUES(%(a)s,%( b)s,%(c)s)",
{ 'tb':tablename, 'a':first data, 'b':second data, etc... }
Jul 18 '05 #2
Pierre-Frédéric Caillaud wrote:
sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s )", datavalue"

- what are the "," doing here if you are trying to build a string ?
- you should use the python povided way which is better (yours looks
like php)

cursor.execute( "INSERT INTO %(tb)s VALUES(%(a)s,%( b)s,%(c)s)", {
'tb':tablename, 'a':first data, 'b':second data, etc... }


Better still, create the query string with the right table name in it
and parameter markers for the data:

sqlquery = "INSERT INTO %s VALUES (%%s, %%s, %%s)" % tablename

Supposing tablename is "customer" this gives

"INSERT INTO customer VALUES (%s, %s, %s)"

Then you can use the parameter substitution mechanism of the DB API to
insert your data in there. Suppose datavalue is ("Steve", "Holden", 85)
then you would do

cursor.execute( sqlquery, datavalue)

The problem with building the data portion of the statement is having to
put the single quotes in around strings and escape any single quotes
that might occur in the values you present. It's much easier to use the
parameter substitution mechanism, even though that *can't* be used to
change a table name in most SQL implementations .

I've assumed for the sake of argument that you're using MySQLdb, which
uses the "%s" paramstyle. mxODBC, for example, you'd use the "?" style,
which makes building statements rather easier.

One final comment: it's much safer to use the column names in INSERT, as in

INSERT INTO customer (First, Last, age)
VALUES ('Steve', 'Holden', 95)

because that isolates you from a change in the column ordering, which
can happen during database reorganizations when you insert a new column
without thinking about the consequences. Just paranoia induced by years
of experience, and therefore often effort-saving.

regards
Steve
Jul 18 '05 #3
Steve Holden wrote:
Pierre-Frédéric Caillaud wrote:
sqlquery = "INSERT INTO %s", tablename + " values(%s,%s,%s )", datavalue"

- what are the "," doing here if you are trying to build a string ?
- you should use the python povided way which is better (yours looks
like php)

cursor.execute( "INSERT INTO %(tb)s VALUES(%(a)s,%( b)s,%(c)s)", {
'tb':tablename, 'a':first data, 'b':second data, etc... }


Better still, create the query string with the right table name in it
and parameter markers for the data:

sqlquery = "INSERT INTO %s VALUES (%%s, %%s, %%s)" % tablename

Supposing tablename is "customer" this gives

"INSERT INTO customer VALUES (%s, %s, %s)"

Then you can use the parameter substitution mechanism of the DB API to
insert your data in there. Suppose datavalue is ("Steve", "Holden", 85)
then you would do

cursor.execute( sqlquery, datavalue)

The problem with building the data portion of the statement is having to
put the single quotes in around strings and escape any single quotes
that might occur in the values you present. It's much easier to use the
parameter substitution mechanism, even though that *can't* be used to
change a table name in most SQL implementations .

I've assumed for the sake of argument that you're using MySQLdb, which
uses the "%s" paramstyle. mxODBC, for example, you'd use the "?" style,
which makes building statements rather easier.

One final comment: it's much safer to use the column names in INSERT, as
in

INSERT INTO customer (First, Last, age)
VALUES ('Steve', 'Holden', 95)

because that isolates you from a change in the column ordering, which
can happen during database reorganizations when you insert a new column
without thinking about the consequences. Just paranoia induced by years
of experience, and therefore often effort-saving.

regards
Steve

Thanks for the help, sorry I posted this twice, my news reader was not
showing the original post so i resubmitted it. I normally work with php
thats why I was trying to build it as a string. I now see how I can load
the data values from my variables, however is the same possible for the
fields? I know you say its best to specify the column names etc however my
script is parsing a web page and getting the field headings (which will
stay the same), data and table name so I wanted to make the script handle
all this rather than having to have a seperate cursor.execute( ) for each
table I want to update - does this make sense?

Regards

Rigga
Jul 18 '05 #4

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

Similar topics

8
2339
by: Kamil | last post by:
i dont know what i'm doing wrong i'm trying to get all the fields from a specific row by user name i'm using php and i got the connection string down and i made a query like this: $query = mysql_query("SELECT * FROM <DBname> WHERE name = $_POST"); the variable $_POST was passed to the php code from a previous html form i get the error: Unknown column '<username here>' in 'where clause'
1
2348
by: iksrazal | last post by:
Hi all, I've been struggling to make this command work from Java: /usr/bin/mysql c4 --user=root --password=mypass -e "source /home/crissilva/c4.sql" Works fine as shown when run from the shell. Using my Java program I get:
6
2785
by: sheree | last post by:
I would like to create a query where one of the columns of the queries comes from a combo list box on a form. For example, if my table has the following fields: id name interest1 interest2 interest3 my combo box would be a dropdown containing these choices:
1
5428
by: Joe | last post by:
Hello All, I am trying to insert a record in the MS Access DB and for some reason I cannot get rid of error message, System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement. And the line it shows in red is cmd.ExecuteNonQuery()
0
5578
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted ******************************************************** For this teeny job, please refer to: http://feeds.reddit.com/feed/8fu/?o=25
5
2027
by: deaconj999 | last post by:
Hi, I have nearly finished my database and I would like to add a query that uses a combo box to get the results, not the usual paramater style input. I suppose it would need a form and a query and a combo box, but where to start !!!!!!!! Any kind soul out there that can give me an example of where to start..........?
2
2623
by: dmstn | last post by:
Hey! I've got a little problem. I have to make a web site for a university essay. I curently have to create a search engine. Users can enter a hotel name in a search bar and results have to appear in another screen. All of this has to be done with java servlets. I think there's something I don't see and it's wrong. My problem is that anything I enter in the search bar appears as a result in the results page, even if there's not such a name in...
3
1502
by: fantomel | last post by:
<?php /* Create the mysql class_exists */ class mysql {
0
9721
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
10640
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
10120
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
6881
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
5550
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5689
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
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
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
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.