I need to set some user meta in my wordpress through local python script. Hence I can't use the WP update_user_meta for it - it has to be done manually.
import mysql.connector as mysql
cnx = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
cursor = cnx.cursor()
get_meta = ("SELECT * FROM `ff_usermeta` WHERE `user_id`= 1 AND (`meta_key`='nickname' OR `meta_key`='info' OR `meta_key`='bg' OR `meta_key`='avatar' OR `meta_key`='profile_updated')")
cursor.execute(get_meta)
meta = cursor.fetchall()
#some processing of the result
cursor.execute(q, (...))
cnx.commit()
cursor.close()
cnx.close()
Now I need to check if the result has meta with each of the keys.
If the key already exists for this user, it needs to run UPDATE for this meta.
If this user still has no meta of this key, it has to INSERT new row.
if(there's no 'nickname' in meta_key on either of 5 or less rows):
q = ("INSERT INTO `ff_usermeta` ...")
else:
q = ("UPDATE `ff_usermeta` ...")
...and 4 more times like that?.. Seems like a good place for a cycle, but I don't really like the idea to make it 5x queues, especially since there might be more fields in the future.
I was thinking along the lines of searching the fetchall result for matches in meta_key, and if found, adding required data to one array, if not - to another. And then just running one update and one insert at the end, assuming both are not empty. If I were to write it in semi-php style, it would look roughly like this:
if(in_array("nickname", meta))
for_update .= "`nickname`='"+data[0]+"', "
else:
fields .= "`nickname`, "
vals .= "'"+data[0]+"', "
if(in_array("bg", meta)):
for_update .= "`bg`='"+data[1]+"', "
else:
fields .= "`bg`, "
vals .= "'"+data[1]+"', "
if(for_update):
update = ("UPDATE `ff_usermeta` SET "+for_update+" WHERE 1")
if(fields):
insert = ("INSERT INTO `ff_usermeta`("+fields+") VALUES ("+vals+")")
But absolutely no clue how to translate it correctly to python. I had to google it up to things like "why dot not working to add one string to another". Any advice? Or perhaps there is a better way? Thanks!
It is not complete, you can not update your rows in that way.
But with this you can start to make your query
The frist select gets exactly 1 row, if the user_id exists.
The user_id doesn't seem the right choice for this, but to get what you can do it is enough.
If the query doesn't have an entry, the it will insert some data you get from anywhere
The update as the insert are in that form wrong as you have to insert 5 new orws or update max 5 rows, but that is more for you to programm
import mysql.connector as mysql
HOST = "localhost"
DATABASE = ""
USER = "root"
PASSWORD = "mypassword"
cnx = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
cnx = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
cursor = cnx.cursor()
user_id = 1
get_meta = ("""SELECT umeta_id, user_id , MAX(IF( `meta_key`='nickname', meta_value,'')) AS 'nickname' , MAX(IF( `meta_key`='info', meta_value,'')) AS 'info' , MAX(IF( `meta_key`='bg', meta_value,'')) AS 'bg' , MAX(IF( `meta_key`='avatar', meta_value,''NULL'')) AS 'avatar' , MAX(IF (`meta_key`='profile_updated', meta_value,'')) AS 'profile_updated' FROM `ff_usermeta` WHERE `user_id`= %s GROUP BY umeta_id, user_id:""")
result = cursor.execute(get_meta,(user_id,))
if result > 0:
data = cursor.fetchone()
for_update = "";
#some processing of the result
if not data["nickname"]:
for_update += "`nickname`='"+data["nickname"]+"', "
if not data["bg"]:
for_update += "`bg`='"+data["bg"]+"', "
query = ("UPDATE `ff_usermeta` SET "+for_update+" WHERE user_id = " + user_id)
else:
#here are no data to be gathered as there is no user_id present add new user
nickname = ""
bg= ""
info = ""
avatar = ""
profile_updated = ""
fields= ""
vals = ""
fields += "`nickname`,`info`, `bg`,`avatar`,`profile_updated`"
vals += "'"+nickname+"', "+"'"+info+"', "+"'"+bg+"', "+"'"+avatar+"', "+"'"+profile_updatedfo+"'"
query = ("INSERT INTO `ff_usermeta`("+fields+") VALUES ("+vals+")")
cursor.execute(query)
cnx.commit()
cursor.close()
cnx.close()
I tried my best to adapt the suggestion above, but couldn't figure out how to make it work. Eventually I went another way, and it seems to work somehow, so I'll post the full code in case anyone would find it useful.
What it does: checks the queue in table with validation request, then parses a page (separate function) and updates user profile accodringly.
import mysql.connector as mysql
import time
from datetime import datetime
cnx = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
while True: #endless loop as a temporary scheduler
cursor = cnx.cursor()
#getting first request in the queue - 0: id, 1: url, 2: parse, 3: status, 4: user, 5: user_page, 6: req_date, 7: action
cursor.execute("SELECT * FROM `ff_qq` WHERE status = 0 LIMIT 1")
row = cursor.fetchone()
if row:
status = 1 #processed
if row[7] == "verify":
get_user = ("SELECT * FROM `ff_users` WHERE ID = %s LIMIT 1")
cursor.execute(get_user, (row[4],))
user = cursor.fetchone() #0 - ID, 5 - user_url, 8 - user_status, 9 - display_name
#separate function that returns data to insert into mysql
udata = verify(row) #0 - nickname, 1 - fb_av, 2 - fb_bg, 3 - fb_info, 4 - owner
ustat = row[1].split("/authors/")
if udata['owned'] or user[8] == ustat[1]:
update_user = ("UPDATE `ff_users` SET user_status = %s, display_name = %s, user_url = %s WHERE ID = %s LIMIT 1")
cursor.execute(update_user, (ustat[1], udata['nickname'], row[1], user[0]))
status = 2 #success
get = ("SELECT `meta_value` FROM `ff_usermeta` WHERE `user_id`= %s AND `meta_key`='ff_capabilities' LIMIT 1")
cursor.execute(get, (row[4],))
rights = cursor.fetchone()
if rights == 'a:1:{s:10:"subscriber";b:1;}':
promote = ("UPDATE `ff_usermeta` SET `meta_value` = 'a:1:{s:6:\"author\";b:1;}' "
"WHERE `user_id` = %s AND `meta_key`='ff_capabilities' LIMIT 1")
cursor.execute(promote, (row[0],))
#list of meta_key values in same order as returned data
ff = ['nickname', 'fb_av', 'fb_bg', 'fb_info']
for x in range(0,3): #goes through each one of the above list
if udata[ff[x]]: #yes this actually works, who would've thought?..
#current meta_key added directly into the string
get = ("SELECT `meta_value` FROM `ff_usermeta` WHERE `user_id`= %s AND `meta_key`='" + ff[x] + "' LIMIT 1")
cursor.execute(get, (row[4],))
meta = cursor.fetchone()
if(meta): #update if it exists, otherwise insert new row
qq = ("UPDATE `ff_usermeta` SET `meta_value` = %s "
"WHERE `user_id` = %s AND `meta_key`='" + ff[x] + "' LIMIT 1")
else:
qq = ("INSERT INTO `ff_usermeta`(`meta_value`, `meta_key`, `user_id`) "
"VALUES ('%s','" + ff[x] + "','%s'")
cursor.execute(qq, (udata[ff[x]], row[0])) #same execute works for both
else:
status = 3 #verification failed
#update queue to reflect its status
update = ("UPDATE `ff_qq` SET status = %s WHERE id = %s LIMIT 1")
cursor.execute(update, (status, row[0]))
cnx.commit()
cursor.close()
now = datetime.now()
print(now.strftime("%d.%m.%Y %H:%M:%S"))
time.sleep(180) #sleep until it's time to re-check the queue
cnx.close()
Related
Newby working my way through python and sql with mariadb.
Why wont this loop? It updates the first record only. Im pretty hack at this...
cursor1.execute("select recordid, mvavgvol, quote_usd_volume_change_24h from pumped")
records = cursor1.fetchall()
for x in records:
rid = (x[0])
m = (x[1])
o = (x[2])
if (m >= o):
result = 0
else:
result = 1
upd_data=(result,rid)
sql1 = ("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s")
cursor2.execute(sql1,upd_data)
conn.commit()
Since you are fetching multiple rows you have to store the fetched values in an array and use cursor's executemany() method instead.
✂
data= []
for x in records:
rid = (x[0])
result= int(x[1] > x[2])
data+= [(result, rid)]
cursor.executemany(UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s", data);
✂
When using mariadb python module (MariaDB Connector/Python) this is much more effective since it reduces network traffic: instead of sending n update commands in a loop (where n is the number of rows in table pumped) only one command will be send to the server.
conn = msql.connect(host=Host,port=Port, user=User, password=Password, database=database)
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select recordid, mvavgvol, quote_usd_volume_change_24h from pumped")
records = cursor1.fetchall()
for x in records:
rid = (x[0])
m = (x[1])
o = (x[2])
if (m >= o):
result = 0
cursor2.execute("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s",(result, rid))
conn.commit()
else:
result = 1
cursor2.execute("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s",(result, rid))
conn.commit()
I'm trying to execute the same query but with different data but I always get data the first time. The others times, dispite of there are data for the querys in the data base, mysql returns empty data.
This is the code:
def get_team_colour_map(self, players, id_competition):
tcm = FIBAColourMap()
for p in players:
args = [p["id"], id_competition]
conn = pymysql.Connect(host = DDBB.DDBB_FIBA_HOST,
user = DDBB.DDBB_FIBA_USER,
password = DDBB.DDBB_FIBA_PSWD,
db = DDBB.DDBB_FIBA_NAME,
charset = DDBB.DDBB_FIBA_CHARSET,
cursorclass=pymysql.cursors.DictCursor)
with conn.cursor() as cursor:
print("id player: {}".format(p["id"]))
print("args: {}".format(args))
cursor.execute("select sc.* from tbl030_shots_chart sc, tbl006_player_team pt, tbl007_game g, tbl004_jornada j, tbl012_competition c where pt.id = %s and pt.id_player_feb = sc.id_fiba and sc.id_game = g.id and g.id_jornada = j.id and j.id_competition = c.id and c.id = %s", args)
data = cursor.fetchall()
print("data: {}".format(data))
print("Total rows: {}".format(cursor.rowcount))
if cursor.rowcount > 0:
for s in data:
x = float(FIBASCReport.adjust_x(s["x"]))
y = float(FIBASCReport.adjust_y(s["y"]))
color = tcm.image.getpixel((x,y))
color = ("#%02x%02x%02x" % color).upper()
if tcm.exists_color(color):
if int(s["m"]) == 0:
tcm.set_scored_shots(color, 1)
else:
tcm.set_failed_shots(color, 1)
else:
if int(s["m"]) == 0:
tcm.set_scored_shots("OTROS", 1)
else:
tcm.set_failed_shots("OTROS", 1)
else:
#tcm = None
print("Jugadora con id: {} NO ha realizado ningún tiro en competición: {}".format(p["id"], id_competition))
return tcm
In this code, cursor.fetchall() returns data the first query but the next querys returns empty results.
How can I run several querys? I'm using mySQL 8.0 and Python 3.6
Its because you are using the same cursor each time. create a new instance of the cursor each time you loop through to excecute the query. After the first query is run the cursor is already positioned after all the data. Hence no rows returned after that
You can also try this:
Look at the documentation for MySQLCursor.execute().
It claims that you can pass in a multi parameter that allows you to run multiple queries in one string.
If multi is set to True, execute() is able to execute multiple statements specified in the operation string.
multi is an optional second parameter to the execute() call:
operation = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cursor.execute(operation, multi=True):
My usecase is to write create a temp table in the postgres database and fetch records from it and insert into a different table.
The code i used is:
import psycopg2
import sys
import pprint
from __future__ import print_function
from os.path import join,dirname,abspath
import xlrd
import os.path
newlist = []
itemidlist = []
def main():
conn_string = "host='prod-dump.cvv9i14mrv4k.us-east-1.rds.amazonaws.com' dbname='ebdb' user='ebroot' password='*********'"
# print the connection string we will use to connect
# print "Connecting to database" % (conn_string)
# get a connection, if a connect cannot be made an exception will be raised here
conn = psycopg2.connect(conn_string)
# conn.cursor will return a cursor object, you can use this cursor to perform queries
cursor = conn.cursor()
dealer_id = input("Please enter dealer_id: ")
group_id = input("Please enter group_id: ")
scriptpath = os.path.dirname('__file__')
filename = os.path.join(scriptpath, 'Winco - Gusti.xlsx')
xl_workbook = xlrd.open_workbook(filename, "rb")
xl_sheet = xl_workbook.sheet_by_index(0)
print('Sheet Name: %s' % xl_sheet.name)
row=xl_sheet.row(0)
from xlrd.sheet import ctype_text
print('(Column #) type:value')
for idx, cell_obj in enumerate(row):
cell_type_str = ctype_text.get(cell_obj.ctype, 'unknown type')
#print('(%s) %s %s' % (idx, cell_type_str, cell_obj.value))
num_cols = xl_sheet.ncols
for row_idx in range(0, xl_sheet.nrows): # Iterate through rows
num_cols = xl_sheet.ncols
id_obj = xl_sheet.cell(row_idx, 1) # Get cell object by row, col
itemid = id_obj.value
#if itemid not in itemidlist:
itemidlist.append(itemid)
# execute our Query
'''
cursor.execute("""
if not exists(SELECT 1 FROM model_enable AS c WHERE c.name = %s);
BEGIN;
INSERT INTO model_enable (name) VALUES (%s)
END;
""" %(itemid,itemid))
'''
cursor.execute("drop table temp_mbp1")
try:
cursor.execute("SELECT p.model_no, pc.id as PCid, g.id AS GROUPid into public.temp_mbp1 FROM products p, \
model_enable me, products_clients pc, groups g WHERE p.model_no = me.name \
and p.id = pc.product_id and pc.client_id = %s and pc.client_id = g.client_id and g.id = %s"\
% (dealer_id,group_id)
except (Exception, psycopg2.DatabaseError) as error:
print(error)
cursor.execute("select count(*) from public.temp_mbp1")
# retrieve the records from the database
records = cursor.fetchall()
# print out the records using pretty print
# note that the NAMES of the columns are not shown, instead just indexes.
# for most people this isn't very useful so we'll show you how to return
# columns as a dictionary (hash) in the next example.
pprint.pprint(records)
if __name__ == "__main__":
main()
The try except block in between the program is not throwing any error but the table is not getting created in the postgres database as i see in the data admin.
The output shown is:
Please enter dealer_id: 90
Please enter group_id: 13
Sheet Name: Winco Full 8_15_17
(Column #) type:value
[(3263,)]
Thanks,
Santosh
You didn't commit the changes, so they aren't saved in the database. Add to the bottom, just below the pprint statement:
conn.commit()
I am having a problem with data corruption. I save the data after encripting in to a dabase. But when compare the same data after retriving, I found that value is not equal.
For me it seems, data is changed after saving data.
RPasswd = "pw2013"
Passwd = "2password"
TVkey = hashlib.sha256(Passwd).digest()
#encode password for before encryption to remove special characters
Rencoded = base64.b64encode(RPasswd)
#pad the length to a multiple of 16 with a space character for encryption
Rencoded += ((16 - len(Rencoded)%16) * " ")
#encrypt password to be stored as the user's credentials
encRPasswd = AES.new(TVkey, AES.MODE_ECB).encrypt(Rencoded)
# Open database connection
db = MySQLdb.connect("localhost","root","root","db" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
try:
cursor.execute("select `group_id`, `group`, `password` from db.groups where group_id = 1 ")
#print "number of rows" + cursor.rowcount
results = cursor.fetchall()
for row in results:
print row[0]
print row[1]
pw = row[2]
print "test"
db.commit()
except:
db.rollback()
# disconnect from server
db.close()
if encRPasswd == pw:
print "samme"
else:
print "not same"
When I run the code I get not same. Ideally, both values should be same.
Any hint?
This is my first post here and I found so many answers here I am really confident, that some can help me. Because I work with Python for only about half a year now, it maybe is a very stupid beginners question. Forgive me so far...
In my project I have several different functions. Two of them are listed below. mysqlLogbookIndex is a thread witch show refresh a list with the names of some table from a database. The connection to the DB is existing at the moment, the function is called and so far it works fine. At the end I can see a tuple containing all the table names.
But now the second function, named create_flight comes in. It is a callback for a Tkinter button and creates some new tables in my database. It uses the same preopened connection than mysqlLogbookIndex.
I expected to see the new tables is my tuple in the next cycle of mysqlLogbookIndex but what happened is that result turned into a None.
Do you know why?
Widget function:
def create_flight(self):
# *********************************************************************************************
# * Create new flight table *
# *********************************************************************************************
if self.sql_write.get():
# ********************************************
# * Try to connect message *
# ********************************************
self.printLog(self.lbl_sql_write, self.LANG['tryCreateTable'], 'normal')
logging.info('Creating table for flight tracking...')
# ********************************************
# * Create name tables *
# ********************************************
event = self.oprSett['mysql']['event']
now = str(int(time.time()))
mainName = "tbl_%s_%s_" % (event, now)
trackingTable = mainName + "flighttrack"
logging.debug('Name of tracking table: %s', trackingTable)
unitsTable = mainName + "units"
logging.debug('Name of units table: %s', unitsTable)
headerTable = mainName + "header"
logging.debug('Name of header table: %s', headerTable)
# ********************************************
# * Read SQL parameter *
# ********************************************
logging.debug('Reading CSV file for table structure...')
csvFile = "config/newFlight.csv"
try:
sqlCsv = csv.reader(open(csvFile, 'rb'),
delimiter = ',',
quotechar = '"',
quoting = csv.QUOTE_ALL
)
except:
msg = csvFile
msg += "\n\n"
msg += self.LANG['e13']
tkMessageBox.showerror("Error 13", msg)
self.printLog(self.lbl_sql_write, self.LANG['e13'], 'error')
logging.error('File not found!')
#print "[Error 13] " + self.LANG['e13']
return 0
# Transfer data from CSV file into own list
sqlVars = []
for row in sqlCsv:
if len(row) == 4 and row[0][0] != "#": # No comment
sqlVars.append(row)
# *************************************************
# * Create SQL statement to create tracking table *
# *************************************************
# Head for creating new table
sql = "CREATE TABLE IF NOT EXISTS `%s` (\n" % trackingTable
sql += " `ID` int(11) NOT NULL AUTO_INCREMENT,\n" # Becomes primary key
# Parse SQL variables from CSV file
for row in sqlVars:
if len(row[2]) > 0: # Data type requires length
sql += " `%s` %s(%s) NOT NULL COMMENT '%s',\n" % (row[0], row[1], row[2], row[3])
else: # Data type not requires length
sql += " `%s` %s NOT NULL COMMENT '%s',\n" % (row[0], row[1], row[3])
# Footer of SQL statement for creating new table
sql += " PRIMARY KEY (`ID`)\n"
sql += ") ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_german1_ci AUTO_INCREMENT=0;\n"
sql += "\n"
# In debug mode print SQL statement to console
#logging.debug('SQL statement to create tracking table:\n%s', sql)
# **********************************************
# * Create SQL statement to create units table *
# **********************************************
# Head for creating new table
sql += "CREATE TABLE IF NOT EXISTS `%s` (\n" % unitsTable
sql += " `ID` int(11) NOT NULL AUTO_INCREMENT,\n" # Becomes primary key
sql += " `Dataref` varchar(10) COLLATE latin1_german1_ci NOT NULL,\n"
sql += " `Unit` varchar(10) COLLATE latin1_german1_ci NOT NULL,\n"
sql += " PRIMARY KEY (`ID`)\n"
sql += ") ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_german1_ci AUTO_INCREMENT=1 ;\n"
sql += "\n"
# Parse SQL variables from CSV file
for row in sqlVars:
# Insert units in tbl_units
sql += "INSERT INTO %s VALUES ('', '%s', '%s');\n" % (unitsTable, row[0], row[3])
sql += "\n"
# In debug mode print SQL statement to console
#logging.debug('SQL statement to create units table:\n%s', sql)
# ***********************************************
# * Create SQL statement to create header table *
# ***********************************************
# Head for creating new table
sql += "CREATE TABLE IF NOT EXISTS `%s` (\n" % headerTable
#sql += " `ID` int(11) NOT NULL AUTO_INCREMENT,\n" # Becomes primary key
sql += " `Parameter` char(21) COLLATE latin1_german1_ci NOT NULL,\n"
sql += " `Value` varchar(100) COLLATE latin1_german1_ci NOT NULL,\n"
sql += " PRIMARY KEY (`Parameter`)\n"
sql += ") ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_german1_ci AUTO_INCREMENT=1 ;\n"
sql += "\n"
# IGC syntax from: http://carrier.csi.cam.ac.uk/forsterlewis/soaring/igc_file_format/igc_format_2008.html
# Adding header parameters, some values are coming later
sql += "INSERT INTO %s VALUES ('AXXX001', '');\n" % (headerTable) # Manufacturer code
sql += "INSERT INTO %s VALUES ('HFFXA', '035');\n" % (headerTable) # Fix accuracy
sql += "INSERT INTO %s VALUES ('HFDTE', '');\n" % (headerTable) # UTC date of flight
sql += "INSERT INTO %s VALUES ('HFPLTPILOT', '');\n" % (headerTable) # Pilots name
sql += "INSERT INTO %s VALUES ('HFGTYGLIDERTYPE', 'KA8B');\n" % (headerTable) # Glider type
sql += "INSERT INTO %s VALUES ('HFGIDGLIDERID', 'D1389');\n" % (headerTable) # Glider callsign
sql += "INSERT INTO %s VALUES ('HFDTM100DATUM', 'WGS-1984');\n" % (headerTable) # GPS datum
sql += "INSERT INTO %s VALUES ('HFGPSGPS', 'X-PLANE 10');\n" % (headerTable) # Manufacturer of GPS module
sql += "INSERT INTO %s VALUES ('HFFTYFRTYPE', 'FLORIANMEISSNER,HCM');\n" % (headerTable) # Logger type
sql += "INSERT INTO %s VALUES ('HFRFWFIRMWAREVERSION', '%s');\n" % (headerTable, self.VERSION) # Firmware version
sql += "INSERT INTO %s VALUES ('HFRHWHARDWAREVERSION', '%s');\n" % (headerTable, self.XPLANEVERSION) # Hardware version
sql += "INSERT INTO %s VALUES ('HFCCLCOMPETITIONCLASS', 'CLUB');\n" % (headerTable) # Competition class
# ********************************************
# * Handover SQL statement to create table *
# * to DB. *
# ********************************************
logging.debug('SQL statement to create all tables:\n%s', sql)
try:
cur = self.conn.cursor()
cur.execute(sql)
cur.close()
except pymysql.Error, e:
tkMessageBox.showerror("Error 9", self.LANG['e9'])
self.printLog(self.lbl_sql_write, self.LANG['e9'], 'error')
#print "[Error 9] " + self.LANG['e9']
logging.error('Could not create tracking table!')
logging.debug(e)
return 0
# ********************************************
# * Print success message *
# ********************************************
logging.info('Tracking table created.')
self.printLog(self.lbl_sql_write, self.LANG['doneCreateTable'], 'success')
text = self.LANG['flightId'] + " " + trackingTable
self.printLog(self.lbl_sql_write, text, 'normal', timestamp=False)
# Make trackingTable public
self.tableName = trackingTable
# Enable tambour register to write in database
self.tambourInMysql = True
Refresh Loop:
def mysqlLogbookIndex(self):
delay = float(self.oprSett['logbook']['refresh_delay']) / 1000
# ********************************************************************
# * Run only if MySQL connection from writeMysql.py is active *
# ********************************************************************
while self.sql_write.get():
# ********************************************
# * Query to get list with tables *
# ********************************************
logging.info('Querying list with tables from database')
dbName = self.oprSett['mysql']['db']
sql = "SELECT TABLE_NAME\n"
sql += "FROM `information_schema`.`TABLES`\n"
sql += "WHERE `TABLE_SCHEMA` LIKE '%s'" % dbName
try:
cur = self.conn.cursor()
cur.execute(sql)
result = cur.fetchall()
cur.close()
except pymysql.Error, e:
logging.warning('Could not take flights from database!')
logging.debug(e)
self.printLog(self.lbl_sql_write, self.LANG['e20'], 'error')
#continue
else:
logging.info('Logbook refreshed.')
print result
Thanks in advance for all helpful posts...
Found the error more or less. It seems to be a MySQL issue.
In my original idea I connected to DB "hcm" and tried to get some table informations from "information_schema" DB. If the "hcm" was changed the query returned None.
Solution:
I established a second independent MySQL connection in my function for the refresh loop and connected to "information_schema" directly.