Python sqlite check if table exists

Python SQLite3 – проверьте, существует ли таблица

Проверьте, существует ли таблица в базе данных SQLite3

Перед запуском запроса на столе вы можете проверить, присутствует ли таблица в базе данных SQLite3 или нет.

Чтобы проверить, существует ли таблица в базе данных Python SQLite3, вы можете запросить sqlite_master Таблица для имен таблиц, которые соответствуют вашему названию таблицы.

SQL Query.

Запрос SQL, чтобы проверить, присутствует ли таблица с заданным именем в базе данных или нет, приведена ниже.

SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';

где table_name В той случае следует заменить предложение на ваше имя таблицы.

Из результатов этого запроса вы можете проверить, есть ли какие-либо строки, присутствующие в результате. Если в результате есть один ряд, то таблица существует.

Пример 1: Проверьте, существует ли таблица в SQLite3

В нашей предыдущей статье создайте таблицу в Python SQLite3, мы создали таблицу с именем студентов. Теперь в этом примере мы проверим, существует ли таблица программно.

import sqlite3 conn = sqlite3.connect('mysqlite.db') c = conn.cursor() #get the count of tables with the name c.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='students' ''') #if the count is 1, then table exists if c.fetchone()[0]==1 : < print('Table exists.') >#commit the changes to db conn.commit() #close the connection conn.close()

Пример 2: Проверьте, существует ли таблица в базе данных SQLite3 (отрицательный сценарий)

В этом примере мы собираемся проверить негативный сценарий, где таблица с именем манекен Нет в базе данных SQLite3, и мы собираемся проверить его программно.

import sqlite3 conn = sqlite3.connect('mysqlite.db') c = conn.cursor() #get the count of tables with the name c.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='students1' ''') #if the count is 1, then table exists if c.fetchone()[0]==1 : print('Table exists.') else : print('Table does not exist.') #commit the changes to db conn.commit() #close the connection conn.close()

Проверьте, существует ли таблица в памяти (RAM)

Если вы проверяете существование таблицы в памяти (RAM), то в использовании запроса sqlite_temp_master вместо sqlite_master Отказ Образец запроса дается входит.

SELECT name FROM sqlite_temp_master WHERE type='table' AND name='table_name';

Резюме

В этом руководстве примеров Python мы узнали, как проверить, существует ли данная таблица в базе данных SQLite3 или нет.

Читайте ещё по теме:

Источник

Читайте также:  First letter capitalized javascript

Python sqlite3 – Check if Table exists

Before running a query on a table, you can check if the table is present in the sqlite3 database or not.

To check if a table exists in Python sqlite3 database, you can query sqlite_master table for table names that match your table name.

SQL Query

The sql query to check if the table with a given name is present in the database or not, is given below.

SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';

where table_name in the where clause should be replaced with your table name.

From the results of this query, you can check if there are any rows present in the result. If there is one row in the result, then the table exists.

Examples

1. Check if table exists in sqlite3 database

In our previous article, create table in python sqlite3, we have created a table named students. Now, in this example, we will check if the table exists programmatically.

Python Program

import sqlite3 conn = sqlite3.connect('mysqlite.db') c = conn.cursor() #get the count of tables with the name c.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='students' ''') #if the count is 1, then table exists if c.fetchone()[0]==1 : < print('Table exists.') >#commit the changes to db conn.commit() #close the connection conn.close()

2. Check if table exists in sqlite3 database (Negative Scenario)

In this example, we are going to check a negative scenario, where the table named dummy is not present in the sqlite3 database and we are going to verify it programmatically.

Python Program

import sqlite3 conn = sqlite3.connect('mysqlite.db') c = conn.cursor() #get the count of tables with the name c.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='students1' ''') #if the count is 1, then table exists if c.fetchone()[0]==1 : print('Table exists.') else : print('Table does not exist.') #commit the changes to db conn.commit() #close the connection conn.close()

3. Check if table exists in in-memory(RAM)

If you are checking for the existence of an in-memory (RAM) table, then in the query use sqlite_temp_master instead of sqlite_master. A sample query is given beow.

SELECT name FROM sqlite_temp_master WHERE type='table' AND name='table_name';

Summary

In this tutorial of Python Examples, we learned how to check if a given table exists in sqlite3 database or not.

Источник

Check If a Table Exists – Python SQLite3

SQLite Check If Table Exists Or Not

Hey readers! In this article we will be studying how we can check if a table exists using SQLite3. This is all gonna easy for us because we will be using Python and its built-in module SQLite3. So, let us go for it.

Читайте также:  Для удобства создания веб-страниц рекомендуется использовать HTML-редактор

Please note: You should be familiar with SQLite3 and SQL commands.

What’s covered in this article?

  1. Creating a database.
  2. Adding some data to it.
  3. Purposely deleting the table.
  4. Creating a program to check if a table exists in Python

Creating a database using Python SQLite3

In this section we shall create a sample database namely company and add an employee table to it. This table contains the basic info about employees in that company. Make sure you create a new Working Directory that holds all the stuff.

import sqlite3 connection = sqlite3.connect('databases/company.db') # file path # create a cursor object from the cursor class cur = connection.cursor() cur.execute(''' CREATE TABLE employee( emp_id integer, name text, designation text, email text )''') print("Database created successfully. ") # committing our connection connection.commit() # close our connection connection.close()
Database created successfully.

This adds a “company.db” file in the databases folder. This file contains our employee table. It’s an empty table, so let us add some data to it.

Adding Data to a Table using Python SQLite3

Using the “executemany()” function we can insert multiple records at once in our table. So, we will be using the same here:

import sqlite3 connection = sqlite3.connect('databases/company.db') # file path cur = connection.cursor() # creating a list of items records = [(100, 'Arvind Sharma', 'Software Engineer', '[email protected]'), (102, 'Neha Thakur', 'Project Manager', '[email protected]'), (103, 'Pavitra Patil', 'Database Engineer', '[email protected]')] cur.executemany("INSERT INTO employee VALUES (. )", records) print('Data added successfully. ') connection.commit() # close our connection connection.close()

So, these are the records we just added through a Python script.

Purposely deleting the table

Now we will purposely delete the table. We use the default SQL’s DROP TABLE command.

import sqlite3 connection = sqlite3.connect('databases/company.db') connection.execute("DROP TABLE employee") print("Your table has been deleted. ") connection.close()
Your table has been deleted.

Check if a table exists using Python SQLite3

Now, to check whether the table exists or not. We need to write a code that will try to locate that table and if not found it should return a message like: “Table not found!!”. For this purpose the fetchall() function is useful. This enables us to retrieve/access all the information a table contains in SQL. This returns a list of all the info it gets.

  1. The SELECT * FROM table name command tries to retrieve the whole table from the database.
  2. If the table exists it will store it in a list called as data_list using the fetchall() function.
  3. If the data exists it will store it in a list.
  4. If no table exists then it will throw OperationalError from the sqlite3 module.
  5. Handle it through except block and then print a message “no such table: table_name”.
import sqlite3 connection = sqlite3.connect('databases/company.db') cur = connection.cursor() try: cur.execute("SELECT * FROM employee") # storing the data in a list data_list = cur.fetchall() print('NAME' + '\t\tEMAIL') print('--------' + '\t\t-------------') for item in items: print(item[0] + ' | ' + item[1] + '\t' + item[2]) except sqlite3.OperationalError: print("No such table: employee") connection.commit() connection.close()

So, in this way we can detect whether a table in a particular table exists in a database or not.

Читайте также:  Элементы создания таблицы html

Conclusion

In this way, we conclude this article here. I hope the reader has got some knowledge about how to use databases using SQLite3. This may prove a great helping hand to someone who is new to DBs.

Источник

Проверка, существует ли таблица в sqlite3 в Python

Перед выполнением запроса к таблице вы можете проверить, присутствует ли таблица в базе данных sqlite3 или нет.

Чтобы проверить, существует ли таблица в базе данных sqlite3 на Python, вы можете запросить таблицу sqlite_master для имен таблиц, которые соответствуют имени вашей таблицы.

SQL-запрос

Запрос sql для проверки, присутствует ли таблица с заданным именем в базе данных или нет, приведен ниже.

SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';

Где, table_name в предложении where следует заменить на имя вашей таблицы.

По результатам этого запроса вы можете проверить, есть ли в результате какие-либо строки. Если в результате есть одна строка, значит, таблица существует.

Пример 1

В этом примере мы проверим, существует ли таблица.

import sqlite3 conn = sqlite3.connect('mysqlite.db') c = conn.cursor() #get the count of tables with the name c.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='students' ''') #if the count is 1, then table exists if c.fetchone()[0]==1 : < print('Table exists.') >#commit the changes to db conn.commit() #close the connection conn.close()

Пример 2

В этом примере мы собираемся проверить скрипт, когда таблица с именем dummy отсутствует в базе данных sqlite3, и мы собираемся проверить это программно.

import sqlite3 conn = sqlite3.connect('mysqlite.db') c = conn.cursor() #get the count of tables with the name c.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='students1' ''') #if the count is 1, then table exists if c.fetchone()[0]==1 : print('Table exists.') else : print('Table does not exist.') #commit the changes to db conn.commit() #close the connection conn.close()

Проверьте, существует ли таблица в оперативной памяти (RAM)

Если вы проверяете наличие таблицы в памяти (RAM), то в запросе используйте sqlite_temp_master вместо sqlite_master. Ниже приводится образец запроса.

SELECT name FROM sqlite_temp_master WHERE type='table' AND name='table_name';

В этом руководстве на примерах Python мы узнали, как проверить, существует ли данная таблица в базе данных sqlite3 или нет.

Источник

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