473,398 Members | 2,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

python equivalent of php implode


in php-scripts, to insert data to database, i'm doing like this:

...
$query_param = array(
'field0' => 1,
'field1' => 3,
'field2' => $var2,
'field3' => $var3,
);
...

$sql = "INSERT INTO $table (".implode(", ", array_keys($query_param)).") VALUES ('".implode("','", $query_param)."')";

how it can be done, using python (elegantly, without cycles)?
--
Best regards,
Maksim Kasimov
mailto: ka*****@i.com.ua
Jul 19 '05 #1
11 9411
It looks like php's implode(sep, seq) is like sep.join(seq) in Python.

But this is a lousy way to write database queries. You should use the
Python's DB-API interface's execute(statement, parameters) instead.
Assuming that paramstyle is 'qmark', I think it ends up looking
something like this:

items = query_param.items()
keys = [item[0] for item in items]
values = [item[1] for item in items]

# If the query parameters or the table are under
# user control you must take care to validate them
assert table in permitted_tables
for k in query_param.keys():
assert k in permitted_keys

sql = "INSERT INTO %s (%s) values %s" % (
table, ", ".join(keys),
", ".join(["?"] * len(keys))
)
conn.execute(sql, values)

now you don't have to worry that you get the quoting of the values
absolutely right, since db-api does it for you.

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFCbmUbJd01MZaTXX0RApXIAKCEBuvx7QyvqmbNZWaSa6 mBgPT96QCgmLOn
Xfskg0r60jNYB4qen2NA89Y=
=hWkf
-----END PGP SIGNATURE-----

Jul 19 '05 #2
Jeff Epler <je****@unpythonic.net> writes:
items = query_param.items()
keys = [item[0] for item in items]
values = [item[1] for item in items]


Is there some reason not to do:

keys = query_params.keys()
values = query_params.values()

That would seem to be a lot more obvious as to what was going on.

Thanks,
<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 19 '05 #3
Maksim Kasimov wrote:

in php-scripts, to insert data to database, i'm doing like this:

...
$query_param = array(
'field0' => 1,
'field1' => 3,
'field2' => $var2,
'field3' => $var3,
);
...

$sql = "INSERT INTO $table (".implode(", ",
array_keys($query_param)).") VALUES ('".implode("','", $query_param)."')";

how it can be done, using python (elegantly, without cycles)?


sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, ','.params.keys()),
','.join(param.values()))

should do the trick.
--
--------------------------------------
Ola Natvig <ol********@infosense.no>
infoSense AS / development
Jul 19 '05 #4



i'm tying to run example, and then get a traceback. am i something missed?

mysql> create table tmp_tmp (id int not null auto_increment primary key, sd
varchar(255) not null default '', si int not null default 1);
import MySQLdb
db = MySQLdb.connect("localhost", "login", "password", "dbname")
c = db.cursor()
query_param = { .... 'sd' : 'somedata',
.... 'si' : 2,
.... } table = 'tmp_tmp'
keys = query_param.keys()
values = query_param.values()
sql = "INSERT INTO %s (%s) values (%s)" % (table, ", ".join(keys), ", ".join(["?"] * len(keys)) ) c.execute(sql, values)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/local/lib/python2.2/site-packages/MySQLdb/cursors.py", line 95,
in execute
return self._execute(query, args)
File "/usr/local/lib/python2.2/site-packages/MySQLdb/cursors.py", line
108, in _execute
self.errorhandler(self, ProgrammingError, m.args[0])
File "/usr/local/lib/python2.2/site-packages/MySQLdb/connections.py", line
33, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: not all arguments converted


"Mike Meyer" <mw*@mired.org> ???????/???????? ? ???????? ?????????:
news:86************@guru.mired.org... Jeff Epler <je****@unpythonic.net> writes:
items = query_param.items()
keys = [item[0] for item in items]
values = [item[1] for item in items]


Is there some reason not to do:

keys = query_params.keys()
values = query_params.values()

That would seem to be a lot more obvious as to what was going on.

Thanks,
<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more

information.
Jul 19 '05 #5
.... but not in the case when integers are in a dictionary (please, try to
execute your example by yourself first)
"Ola Natvig" <ol********@infosense.no> wrote:
news:kv************@pluto.i.infosense.no...
Maksim Kasimov wrote:

in php-scripts, to insert data to database, i'm doing like this:

...
$query_param = array(
'field0' => 1,
'field1' => 3,
'field2' => $var2,
'field3' => $var3,
);
...

$sql = "INSERT INTO $table (".implode(", ",
array_keys($query_param)).") VALUES ('".implode("','", $query_param)."')";
how it can be done, using python (elegantly, without cycles)?


sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, ','.params.keys()),
','.join(param.values()))

should do the trick.
--
--------------------------------------
Ola Natvig <ol********@infosense.no>
infoSense AS / development

Jul 19 '05 #6
Maxim Kasimov wrote:
i'm tying to run example, and then get a traceback. am i something missed?

mysql> create table tmp_tmp (id int not null auto_increment primary key,
sd varchar(255) not null default '', si int not null default 1);
import MySQLdb
db = MySQLdb.connect("localhost", "login", "password", "dbname")
c = db.cursor()
query_param = { ... 'sd' : 'somedata',
... 'si' : 2,
... } table = 'tmp_tmp'
keys = query_param.keys()
values = query_param.values()
sql = "INSERT INTO %s (%s) values (%s)" % (table, ", ".join(keys), ", ".join(["?"] * len(keys)) ) c.execute(sql, values)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/local/lib/python2.2/site-packages/MySQLdb/cursors.py", line
95,
in execute
return self._execute(query, args)
File "/usr/local/lib/python2.2/site-packages/MySQLdb/cursors.py", line
108, in _execute
self.errorhandler(self, ProgrammingError, m.args[0])
File "/usr/local/lib/python2.2/site-packages/MySQLdb/connections.py",
line
33, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: not all arguments converted


Try another paramstyle (see http://python.org/peps/pep-0249.html), e. g.

.... ",".join(["%s"] * len(keys)) ...

instead of

.... ",".join(["?"] * len(keys)) ...

Peter

Jul 19 '05 #7
On Wed, 27 Apr 2005 08:44:36 +0200, Ola Natvig <ol********@infosense.no>
declaimed the following in comp.lang.python:
sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, ','.params.keys()),
','.join(param.values()))
That also violates the DB-API recommendations that the
..execute() method should be used to do parameter substitution -- to
ensure proper quoting of odd data...

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 19 '05 #8
On Wed, 27 Apr 2005 09:57:29 +0300, "Maxim Kasimov" <ka*****@i.com.ua>
declaimed the following in comp.lang.python:

sql = "INSERT INTO %s (%s) values (%s)" % (table, ", ".join(keys), ", ".join(["?"] * len(keys)) )
And what do the multiple ? represent?

As I read the documentation,
http://sourceforge.net/docman/displa...group_id=22307,
MySQLdb uses "format", not "qmark" placeholders. That means you should
probably be using "%s" instead of "?" in that second join()
paramstyle

String constant stating the type of parameter marker formatting expected by the interface. Set to 'format' = ANSI C printf format codes, e.g. '...WHERE name=%s'. If a mapping object is used for conn.execute(), then the interface actually uses 'pyformat' = Python extended format codes, e.g. '...WHERE name=%(name)s'. However, the API does not presently allow the specification of more than one style in paramstyle.

Note that any literal percent signs in the query string passed to execute() must be escaped, i.e. %%.

Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.


_mysql_exceptions.ProgrammingError: not all arguments converted
Well, if MySQLdb wants %s for argument processing, and you
supplied ?, then none of your supplied values are being converted...
Proper error message for the condition.

I'd normally test my statements before responding -- but I
haven't gotten everything installed on my new computer yet (I think I've
got four databases, but none running... MySQL, MaxDB, Firebird, ignore
JET/Access, SQL Server [SQLExpress]).

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 19 '05 #9

done. thanks


Try another paramstyle (see http://python.org/peps/pep-0249.html), e. g.

.... ",".join(["%s"] * len(keys)) ...

instead of

.... ",".join(["?"] * len(keys)) ...

Peter

--
Best regards,
Maksim Kasimov
mailto: ka*****@i.com.ua
Jul 19 '05 #10
On Tue, Apr 26, 2005 at 09:59:29PM -0500, Mike Meyer wrote:
Jeff Epler <je****@unpythonic.net> writes:
items = query_param.items()
keys = [item[0] for item in items]
values = [item[1] for item in items]


Is there some reason not to do:

keys = query_params.keys()
values = query_params.values()

That would seem to be a lot more obvious as to what was going on.


I was afraid that .keys() and .values() might not "match up" (so that
the i'th key maps to the i'th value in query_param). Now that I've
glanced at the documentation, I see that this *is* guaranteed[1], and
I should have written the code you proposed.

Jeff
[1] http://docs.python.org/lib/typesmapping.html note 3

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD4DBQFCb5TuJd01MZaTXX0RAntjAJ9P/mkn0I89OAGuZg+/p0eD2I1yggCYyXyf
WPsG6NFMvqaM5ZbeViyI3g==
=PfBJ
-----END PGP SIGNATURE-----

Jul 19 '05 #11
On 2005-04-27, Dennis Lee Bieber <wl*****@ix.netcom.com> wrote:
On Wed, 27 Apr 2005 08:44:36 +0200, Ola Natvig <ol********@infosense.no>
declaimed the following in comp.lang.python:
sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, ','.params.keys()),
','.join(param.values()))

That also violates the DB-API recommendations that the
.execute() method should be used to do parameter substitution -- to
ensure proper quoting of odd data...


I would think this would be OK:

keys = params.keys()
columnList = ", ".join(keys)
valueList = ["%%(%s)s" % key for keys]
sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, columnList, valueList)
cursor.execute(sql, params)

Though you would probably want to go further and filter out keys that don't
belong in the table, something like:

keys = [key for key in tableColumns if key in params]

Dave Cook
Jul 19 '05 #12

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

Similar topics

5
by: Andreas Paasch | last post by:
I'm having trouble with the implode function and need some help here. I've been reading at php.net but that didn't solve my problem. I'm having the below code: $query = "SELECT top1, top2,...
3
by: Shawn Campbell | last post by:
Here's my scenario: I'm creating a build environment with one system acting as the main build dispatcher and other systems as the build hosts. On the main build system I have Apache, MySQL and...
11
by: Jeff | last post by:
Hello. Quick background as I dont wish to hog anyones time. I am a customer of a PHP/SQL programmer. A website that I had the programmer build for me is working great, with one exception. I...
26
by: Christoph Zwerschke | last post by:
You will often hear that for reasons of fault minimization, you should use a programming language with strict typing: http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html I...
852
by: Mark Tarver | last post by:
How do you compare Python to Lisp? What specific advantages do you think that one has over the other? Note I'm not a Python person and I have no axes to grind here. This is just a question for...
59
by: Kevin Walzer | last post by:
From the introduction to PyObjC, the Python-Objective-C bridge on Mac OS X: "As described in Objective-C for PyObjC users the creation of Objective-C objects is a two-stage process. To initialize...
18
by: NoWhereMan | last post by:
Maybe a stupid question. ------------------------- 1 ------------------------- $str = ''; for($i=0; $i<10; $i++) $str .= $i;
1
by: scatfly | last post by:
I have a set of values that were put into a form and am now using this to put into a database. this is my error: "Warning: implode() : Bad arguments. in /home/xxxxxx/public_html/login.php on line...
6
by: tokcy | last post by:
Hi, I am having a problem with implode() function in PHP. whenever i am running my code it display an error like. Warning: implode() : Bad arguments. in D:\xampp\htdocs\admin\addspecs.php on...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
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...

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.