我正在使用这个功能:
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 (*)...... "
我怎么检查呢?任何帮助将非常感激。
使用“TABLES”信息架构视图。 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
如果您使用的是Python-MySQL(MySQLdb) - > http://mysql-python.sourceforge.net/MySQLdb.html
cursor.execute()是使用MySQLdb,Python MySQL驱动程序运行查询的方法。您可以传递两个参数,例如:
cursor.execute(statement, parameters)
并将执行“语句”解析“参数”到语句。您需要打开数据库连接并打开游标
我想你可以使用MySQL的声明:SHOW TABLES LIKE'tablename';
stmt = "SHOW TABLES LIKE 'tableName'"
cursor.execute(stmt)
result = cursor.fetchone()
if result:
# there is a table named "tableName"
else:
# there are no tables named "tableName"
编辑:还有其他类似行为的Python驱动程序。寻找你的:)
我发现这适用于Python 3.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!')
以上答案可能不适用于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()