我正在使用这个函数:
def checker(name,s)
MY_T = "SELECT count(*) FROM `"+session.SessionInfo.Name where EventName='"+name+"'"
我想查询表是否存在,怎么做?我看到一些使用XXXX.execute()
的例子:它是什么意思?
这是我所看到的:
query = cursor.execute("""SELECT count(*) FROM scan WHERE prefix = %s and code_id = %s and answer = %s and station_id = %s""",
(prefix, code_id, answer, station,))
if query != 1:
例如,我尝试打印MY_T以查看它是否返回-1,但它只打印"select count (*)...... "
我该怎么检查呢?任何帮助都将不胜感激。
发布于 2013-06-11 20:42:54
使用“表”信息架构视图。http://dev.mysql.com/doc/refman/5.0/en/information-schema.html
SELECT * FROM information_schema.tables
WHERE table_name = 'YOUR TABLE'
您可以通过执行以下操作将此视图应用于您的代码:
def checkTableExists(dbcon, tablename):
dbcur = dbcon.cursor()
dbcur.execute("""
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_name = '{0}'
""".format(tablename.replace('\'', '\'\'')))
if dbcur.fetchone()[0] == 1:
dbcur.close()
return True
dbcur.close()
return False
发布于 2018-08-18 05:34:04
上面的答案可能不适用于Oracle,我发现以下代码片段适用于Oracle:
import cx_Oracle
def checkTableExists(dbcon, tablename):
dbcur = dbcon.cursor()
try:
dbcur.execute("SELECT * FROM {}".format(tablename))
return True
except cx_Oracle.DatabaseError as e:
x = e.args[0]
if x.code == 942: ## Only catch ORA-00942: table or view does not exist error
return False
else:
raise e
finally:
dbcur.close()
发布于 2018-01-20 02:16:03
我发现这在Python3.6和MySql 5.7中工作得很好:
table = 'myTable'
_SQL = """SHOW TABLES"""
cursor.execute(_SQL)
results = cursor.fetchall()
print('All existing tables:', results) # Returned as a list of tuples
results_list = [item[0] for item in results] # Conversion to list of str
if table in results_list:
print(table, 'was found!')
else:
print(table, 'was NOT found!')
https://stackoverflow.com/questions/17044259
复制相似问题