Python sqlalchemy get table

How to use Python and SQLAlchemy to get a list of all table names in a SQLite database ?

Using SQLAlchemy and Python, you can get a list of all the tables in a SQLite database.

Import SQLAlchemy

First, import the necessary modules: ‘SQLAlchemy’. This will allow you to use the SQLAlchemy library and connect to a Sqlite database.

import sqlalchemy import pkg_resources pkg_resources.get_distribution("sqlalchemy").version 

Create an instance of the SQLAlchemy Engine class

The first step is to create an engine object, which will connect your program with the database.

engine = sqlalchemy.create_engine('sqlite:///database_name.db') 

For example using the chinook.db databse:

engine = sqlalchemy.create_engine('sqlite:///chinook.db') 

Get a list of all table names using get_table_names

After that, use the Inspector class provided by the SQLAlchemy library to inspect the database. You will be able to access information about the tables, columns and constraints from this inspector. Finally, use the inspector’s get_table_names method to get a list of all the table names in the database. You can then loop through this list and access or manipulate each table as needed.

['CUSTOMER', 'PRODUCT', 'albums', 'artists', 'customers', 'employees', 'genres', 'invoice_items', 'invoices', 'media_types', 'playlist_track', 'playlists', 'sqlite_sequence', 'sqlite_stat1', 'tracks'] 

Extract table names from MetaData

META_DATA = sqlalchemy.MetaData(bind=engine) META_DATA.reflect() META_DATA.tables.keys() 
dict_keys(['CUSTOMER', 'PRODUCT', 'albums', 'artists', 'customers', 'employees', 'genres', 'invoice_items', 'invoices', 'tracks', 'media_types', 'playlist_track', 'playlists', 'sqlite_sequence', 'sqlite_stat1']) 

Check if table exists

The most robust way of doing this is by using the ‘has_table()’, which returns a Boolean value indicating whether or not that table has been created already in your database. An example of this is shown below:

sqlalchemy.inspect(engine).has_table("customers") 

If the value returned by ‘exists’ is False, then the table does not exist in your database:

sqlalchemy.inspect(engine).has_table("shope") 

References

Источник

Читайте также:  Html body style javascript

SQLAlchemy — получение списка таблиц

Я не мог найти никакой информации об этом в документации, но как я могу получить список таблиц, созданных в SQLAlchemy? Я использовал метод класса для создания таблиц.

8 ответов

Все таблицы собраны в tables атрибутов объекта SQLAlchemy MetaData. Чтобы получить список имен этих таблиц:

>>> metadata.tables.keys() ['posts', 'comments', 'users'] 

Если вы используете декларативное расширение, вы, вероятно, не управляете метаданными самостоятельно. К счастью, метаданные все еще присутствуют в базовом классе,

>>> Base = sqlalchemy.ext.declarative.declarative_base() >>> Base.metadata MetaData(None) 

Если вы пытаетесь выяснить, какие таблицы присутствуют в вашей базе данных, даже среди тех, о которых вы еще даже не говорили SQLAlchemy, то вы можете использовать отражение таблиц. Затем SQLAlchemy проверит базу данных и обновит метаданные всеми отсутствующими таблицами.

Устаревший с версии 0.8: используйте метод sqlalchemy.schema.MetaData.reflect (). И обратите внимание, используйте engine = sqlalchemy.create_engine(‘mysql://user:[email protected]/db_name’) вместо «mysql://user:[email protected]» и engine.execute(«use db_name») .

@XuJiawan: я не уверен, какая вещь здесь не рекомендуется, я не уверен, какой метод я предлагаю, если это не sqlalchemy.MetaData.reflect() ?

@XuJiawan: ссылка предполагает, что аргумент reflect для MetaData.__init__ , логический флаг, устарел в пользу использования MetaData.reflect() , именно так, как я показал в своем ответе.

@IfLoop: Очень сожалею о моем плохом английском. Твой ответ в точности правильный, и я поднял его. Я добавил этот комментарий просто для того, чтобы люди заметили, что если они используют версию

В объекте engine существует метод для извлечения списка имен таблиц. engine.table_names()

я получаю Traceback (most recent call last): File «dedup_jobs.py», line 31, in print(engine.table_names()) File «/Users/darshanchoudhary/.virtualenvs/services/lib/python3.6/site-packages/sqlalchemy/engine/base.py», line 2128, in table_names return self.dialect.get_table_names(conn, schema) value = value.replace(self.escape_quote, self.escape_to_quote) AttributeError: ‘NoneType’ object has no attribute ‘replace’ (стек урезан)

Я искал что-то вроде этого:

from sqlalchemy import create_engine eng = create_engine('mysql+pymysql://root:[email protected]:3306', pool_recycle=3600) q = eng.execute('SHOW TABLES') available_tables = q.fetchall() 

Он выполняет и возвращает все таблицы.

eng = create_engine('postgresql+psycopg2://root:[email protected]/ q = eng.execute('SELECT * FROM pg_catalog.pg_tables') 

Это не кроссплатформенность. Он будет работать только с MySQL, он не будет работать с другими движками баз данных.

Источник

Оцените статью