Hướng dẫn how do i check if a table exists in python sql? - làm cách nào để kiểm tra xem một bảng có tồn tại trong python sql không?

Tôi đang sử dụng chức năng này:

def checker[name,s]
        MY_T = "SELECT count[*] FROM `"+session.SessionInfo.Name where EventName='"+name+"'"

Tôi muốn kiểm tra xem bảng có tồn tại không, làm thế nào tôi có thể làm điều đó?

Tôi đã thấy một số ví dụ sử dụng

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:
2. Nó có nghĩa là gì?

Đây là những gì tôi đã thấy:

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:

Tôi đã thử in my_t để xem nó có trả về -1 chẳng hạn nhưng nó chỉ in

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:
3

Làm thế nào tôi có thể kiểm tra nó?

Đã hỏi ngày 11 tháng 6 năm 2013 lúc 12:35Jun 11, 2013 at 12:35

user1386966user1386966user1386966

3.20213 Huy hiệu vàng39 Huy hiệu bạc69 Huy hiệu đồng13 gold badges39 silver badges69 bronze badges

3

Sử dụng chế độ xem lược đồ thông tin "bảng". //dev.mysql.com/doc/refman/5.0/en/information-schema.html

SELECT * FROM information_schema.tables
WHERE table_name = 'YOUR TABLE'

Bạn có thể áp dụng chế độ xem này vào mã của mình bằng cách làm một cái gì đó như sau:

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

Đã trả lời ngày 11 tháng 6 năm 2013 lúc 12:42Jun 11, 2013 at 12:42

4

Nếu bạn đang sử dụng python-mysql [mysqldb]-> //mysql-python.sourceforge.net/mysqldb.html

con trỏ.execute [] là phương thức chạy các truy vấn với MySQLDB, Trình điều khiển Python MySQL. Bạn có thể vượt qua hai đối số, như:

cursor.execute[statement, parameters]

Và sẽ thực thi "câu lệnh" phân tích cú pháp "tham số" cho câu lệnh. Bạn cần phải mở kết nối cơ sở dữ liệu và cũng mở con trỏ

Tôi nghĩ rằng bạn có thể sử dụng câu lệnh của MySQL: Hiển thị các bảng như 'TableName';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"

EDIT: Sẽ có các trình điều khiển Python khác với hành vi tương tự. Tìm kiếm của bạn :]

Đã trả lời ngày 11 tháng 6 năm 2013 lúc 13:07Jun 11, 2013 at 13:07

Alberto Megíaalberto MegíaAlberto Megía

2.1753 huy hiệu vàng22 Huy hiệu bạc33 Huy hiệu đồng3 gold badges22 silver badges33 bronze badges

Câu trả lời trên có thể không hoạt động cho Oracle, tôi đã tìm thấy đoạn mã bên dưới công việc cho 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[]

Đã trả lời ngày 17 tháng 8 năm 2018 lúc 21:34Aug 17, 2018 at 21:34

1

Tôi thấy rằng điều này hoạt động tốt với Python 3.6 và 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!']

Đã trả lời ngày 19 tháng 1 năm 2018 lúc 18:16Jan 19, 2018 at 18:16

Hãy thử mã này nó hiển thị tất cả các bảng. Sau đó, so sánh tên bảng đã lưu với bảng mục tiêu của bạn

Thay đổi con trỏ thành bạn trong mã của bạn ^_ ^

def tableExistance[table_name]:

    cursor.execute['SHOW tables;']

    myresult = cursor.fetchall[]

    for loacal_table_name in myresult:

        print['table name', loacal_table_name[0]]
    
        if loacal_table_name[0] == table_name:
        
            return True
    
    return False

exist = tableExistance["you table name"]
print['tableExistance', exist]

Đã trả lời ngày 5 tháng 11 lúc 10:48Nov 5 at 10:48

Tôi nghĩ rằng cách đơn giản nhất là sử dụng:

SELECT COUNT[*] = 1 as exists FROM pg_tables WHERE tablename = 'my_table';

điều đó trở lại nếu bảng tồn tại:

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:
0

hoặc trong Python bằng cách sử dụng

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:
4:

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:
1

Đã trả lời ngày 23 tháng 11 năm 2021 lúc 12:04Nov 23, 2021 at 12:04

điều chỉnhtuned

1.05710 Huy hiệu bạc14 Huy hiệu đồng10 silver badges14 bronze badges

Bài Viết Liên Quan

Chủ Đề