[newbie] - python list into a sql query
João
joaopcf at gmail.com
Mon Mar 1 12:54:20 EST 2010
Hi.
Can someone guide me into getting this to work? It's just really
querying a DB of an Autodiscovery tool to have a bunch of updated dns
files.
(Thought I'm still building the first script steps) I was able to
successfully query the DB against a single groupid, but am failing in
passing a list of integers into the sql query.
I'm failing miserably in,
sql = '''SELECT ip, host, dns FROM zabbix_tst_db.hosts WHERE hostid IN
(
select hostid from hosts_groups WHERE groupid IN (' +
','.join(map(str, %s)) + ')''' % grp_range
with
_mysql_exceptions.ProgrammingError: (1064, "You have an error in
your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near '' at line 1")
I'll gladly accept any other code change suggestion
#!/usr/bin/env python
import MySQLdb
import sys, os
import code
builder_path = '/opt/scripts/dns_builder'
grp_range = range(10,15)
try:
db = MySQLdb.connect(host="localhost",
user="tst",passwd="tst",db="tst_db" )
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
cursor = db.cursor()
sql = '''SELECT ip, host, dns FROM zabbix_tst_db.hosts WHERE
hostid IN (
select hostid from hosts_groups WHERE groupid IN (' +
','.join(map(str, %s)) + ')''' % grp_range
cursor.execute(sql)
f = open('%s/dns_unknown_list.txt', 'w+') % builder_path
data = cursor.fetchall()
for row in data:
ip = row[0]
host = row[1]
dns = row[2]
if host == dns:
#tmn
if ip[0][:10] in ('140.254.30','10.13.74.')
group1_file = open('%s/group1.zone', 'w') % builder_path
print >>group1_file, '''$ORIGIN group1
'''
print >>group1_file, '%s IN A %s' % (dns, ip)
elif ip[0][:3] in ('8.128.46.','6.128.101')
group2_file = open('%s/group2.zone', 'w') % builder_path
print >>group2_file, '''$ORIGIN group2
'''
print >>group2_file, '%s IN A %s' % (dns, ip)
else:
print >>f, 'unknown IN A %s' % ip
db.close()
input_file.close()
f.close()
More information about the Python-list
mailing list