def check_table_existence(Function_name,database_table_name): try: connection = Function_name cursor = connection.cursor() cursor.execute(f"SELECT 1 FROM {database_table_name} LIMIT 1") result = cursor.fetchone() cursor.close() connection.close() if result: pass else: print(f"连接成功, 但表{database_table_name}不存在。") except pymysql.Error as e: print("Failed to connect or execute query:", str(e)) check_table_existence(get_bakinfo_mysql_connection,'test.bakinfo') Traceback (most recent call last): File "/root/test/4.py", line 354, in <module> check_table_existence(get_bakinfo_mysql_connection,'test.bakinfo') File "/root/test/4.py", line 342, in check_table_existence cursor = connection.cursor() AttributeError: 'function' object has no attribute 'cursor'
时间: 2024-04-15 13:28:18 浏览: 68
根据你的代码,错误是因为你将函数名 `Function_name` 直接赋值给了 `connection`,导致无法调用 `cursor()` 方法。你需要在调用函数时,加上括号 `()` 来执行函数并获取返回的数据库连接对象。
修改后的代码如下:
```python
def check_table_existence(connection_func, database_table_name):
try:
connection = connection_func() # 调用函数获取数据库连接对象
cursor = connection.cursor()
cursor.execute(f"SELECT 1 FROM {database_table_name} LIMIT 1")
result = cursor.fetchone()
cursor.close()
connection.close()
if result:
pass
else:
print(f"连接成功, 但表{database_table_name}不存在。")
except pymysql.Error as e:
print("Failed to connect or execute query:", str(e))
check_table_existence(get_bakinfo_mysql_connection, 'test.bakinfo')
```
请确保在调用 `check_table_existence()` 函数时,传递的是获取数据库连接的函数名,并且该函数执行后返回有效的数据库连接对象。这样就能够正常执行检查表是否存在的操作了。
阅读全文