your programing

테이블이 있는지 SQLite에서 어떻게 확인합니까?

lovepro 2020. 9. 28. 09:51
반응형

테이블이 있는지 SQLite에서 어떻게 확인합니까?


특정 사용자 테이블이 있는지 여부를 SQLite에서 어떻게 안정적 으로 확인합니까?

나는 테이블의 "select *"가 오류를 반환했는지 여부를 확인하는 것과 같은 신뢰할 수없는 방법을 요구하지 않습니다 (이것도 좋은 생각입니까?).

그 이유는 다음과 같습니다.

내 프로그램에서 테이블이 아직없는 경우 몇 가지 테이블을 만든 다음 채워야합니다.

이미 존재하는 경우 일부 테이블을 업데이트해야합니다.

문제의 테이블이 이미 생성되었음을 알리기 위해 다른 경로를 취해야합니까? 예를 들어 디스크의 프로그램 초기화 / 설정 파일에 특정 플래그를 생성 / 입력 / 설정하는 등의 방법으로 처리해야합니까?

아니면 내 접근 방식이 의미가 있습니까?


FAQ 항목을 놓쳤습니다.

어쨌든 향후 참조를 위해 전체 쿼리는 다음과 같습니다.

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

{table_name}확인할 테이블의 이름은 어디에 있습니까 ?

참조를위한 문서 섹션 : 데이터베이스 파일 형식. 2.6. SQL 데이터베이스 스키마 저장

  • 이렇게하면 지정된 이름의 테이블 목록이 반환됩니다. 즉, 커서의 개수는 0 (존재하지 않음) 또는 1 (존재)입니다.

SQLite 버전 3.3 이상을 사용하는 경우 다음을 사용하여 테이블을 쉽게 만들 수 있습니다.

create table if not exists TableName (col1 typ1, ..., colN typN)

같은 방법으로 다음을 사용하여 테이블이있는 경우에만 제거 할 수 있습니다.

drop table if exists TableName

변형은 SELECT NAME 대신 SELECT COUNT (*)를 사용하는 것입니다.

SELECT count(*) FROM sqlite_master WHERE type='table' AND name='table_name';

테이블이 존재하지 않으면 0을, 존재한다면 1을 반환합니다. 수치 결과를 더 빠르고 쉽게 처리 할 수 ​​있으므로 프로그래밍에 유용 할 것입니다. 다음은 매개 변수가있는 SQLiteDatabase, Cursor, rawQuery를 사용하여 Android에서이를 수행하는 방법을 보여줍니다.

boolean tableExists(SQLiteDatabase db, String tableName)
{
    if (tableName == null || db == null || !db.isOpen())
    {
        return false;
    }
    Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?", new String[] {"table", tableName});
    if (!cursor.moveToFirst())
    {
        cursor.close();
        return false;
    }
    int count = cursor.getInt(0);
    cursor.close();
    return count > 0;
}

시도해 볼 수 있습니다.

SELECT name FROM sqlite_master WHERE name='table_name'

"테이블이 이미 존재 함"오류가 발생하면 다음과 같이 SQL 문자열을 변경하십시오.

CREATE table IF NOT EXISTS table_name (para1,para2);

이렇게하면 예외를 피할 수 있습니다.


SQLite 테이블 이름은 대소 문자를 구분하지 않지만 비교는 기본적으로 대소 문자를 구분합니다. 모든 경우에이 작업이 제대로 작동하도록하려면 COLLATE NOCASE.

SELECT name FROM sqlite_master WHERE type='table' AND name='table_name' COLLATE NOCASE

사용하다:

PRAGMA table_info(your_table_name)

결과 테이블이 비어 있으면 your_table_name존재하지 않습니다.

선적 서류 비치:

PRAGMA schema.table_info (테이블 이름);

이 pragma는 명명 된 테이블의 각 열에 대해 하나의 행을 반환합니다. 결과 집합의 열에는 열 이름, 데이터 형식, 열이 NULL 일 수 있는지 여부 및 열의 기본값이 포함됩니다. 결과 집합의 "pk"열은 기본 키의 일부가 아닌 열의 경우 0이고 기본 키의 일부인 열의 경우 기본 키의 열 인덱스입니다.

The table named in the table_info pragma can also be a view.

Example output:

cid|name|type|notnull|dflt_value|pk
0|id|INTEGER|0||1
1|json|JSON|0||0
2|name|TEXT|0||0

See this:

SELECT name FROM sqlite_master
WHERE type='table'
ORDER BY name;

If you're using fmdb, I think you can just import FMDatabaseAdditions and use the bool function:

[yourfmdbDatabase tableExists:tableName].

The following code returns 1 if the table exists or 0 if the table does not exist.

SELECT CASE WHEN tbl_name = "name" THEN 1 ELSE 0 END FROM sqlite_master WHERE tbl_name = "name" AND type = "table"

Note that to check whether a table exists in the TEMP database, you must use sqlite_temp_master instead of sqlite_master:

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

Here's the function that I used:

Given an SQLDatabase Object = db

public boolean exists(String table) {
    try {
         db.query("SELECT * FROM " + table);
         return true;
    } catch (SQLException e) {
         return false;
    }
}

Use this code:

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

If the returned array count is equal to 1 it means the table exists. Otherwise it does not exist.


Use

SELECT 1 FROM table LIMIT 1;

to prevent all records from being read.


The most reliable way I have found in C# right now, using the latest sqlite-net-pcl nuget package (1.5.231) which is using SQLite 3, is as follows:

var result = database.GetTableInfo(tableName);
if ((result == null) || (result.Count == 0))
{
    database.CreateTable<T>(CreateFlags.AllImplicit);
}

class CPhoenixDatabase():
    def __init__(self, dbname):
        self.dbname = dbname
        self.conn = sqlite3.connect(dbname)

    def is_table(self, table_name):
        """ This method seems to be working now"""
        query = "SELECT name from sqlite_master WHERE type='table' AND name='{" + table_name + "}';"
        cursor = self.conn.execute(query)
        result = cursor.fetchone()
        if result == None:
            return False
        else:
            return True

Note: This is working now on my Mac with Python 3.7.1


Using a simple SELECT query is - in my opinion - quite reliable. Most of all it can check table existence in many different database types (SQLite / MySQL).

SELECT 1 FROM table;

It makes sense when you can use other reliable mechanism for determining if the query succeeded (for example, you query a database via QSqlQuery in Qt).


You can write the following query to check the table existance.

SELECT name FROM sqlite_master WHERE name='table_name'

Here 'table_name' is your table name what you created. For example

 CREATE TABLE IF NOT EXISTS country(country_id INTEGER PRIMARY KEY AUTOINCREMENT, country_code TEXT, country_name TEXT)"

and check

  SELECT name FROM sqlite_master WHERE name='country'

This is my code for SQLite Cordova:

get_columnNames('LastUpdate', function (data) {
    if (data.length > 0) { // In data you also have columnNames
        console.log("Table full");
    }
    else {
        console.log("Table empty");
    }
});

And the other one:

function get_columnNames(tableName, callback) {
    myDb.transaction(function (transaction) {
        var query_exec = "SELECT name, sql FROM sqlite_master WHERE type='table' AND name ='" + tableName + "'";
        transaction.executeSql(query_exec, [], function (tx, results) {
            var columnNames = [];
            var len = results.rows.length;
            if (len>0){
                var columnParts = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').split(','); ///// RegEx
                for (i in columnParts) {
                    if (typeof columnParts[i] === 'string')
                        columnNames.push(columnParts[i].split(" ")[0]);
                };
                callback(columnNames);
            }
            else callback(columnNames);
        });
    });
}

I thought I'd put my 2 cents to this discussion, even if it's rather old one.. This query returns scalar 1 if the table exists and 0 otherwise.

select 
    case when exists 
        (select 1 from sqlite_master WHERE type='table' and name = 'your_table') 
        then 1 
        else 0 
    end as TableExists

Table exists or not in database in swift

func tableExists(_ tableName:String) -> Bool {
        sqlStatement = "SELECT name FROM sqlite_master WHERE type='table' AND name='\(tableName)'"
        if sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement, nil) == SQLITE_OK {
            if sqlite3_step(compiledStatement) == SQLITE_ROW {
                return true
            }
            else {
                return false
            }
        }
        else {
            return false
        }
            sqlite3_finalize(compiledStatement)
    }

참고URL : https://stackoverflow.com/questions/1601151/how-do-i-check-in-sqlite-whether-a-table-exists

반응형