2017-12-14 5 views
0

私の例では、intのリストとデータベースの文字列のリストを格納する必要があります。私は現在、intのリスト全体と文字列のリストを単一のintに変換しています。私はこれが理想的なワークフローかどうか、誰かがこれをどのように処理できるかについての代替の推奨事項があるのだろうかと思っていました。文字列として格納することについての私の懸念は、どうやって遅くなり、intとstringのpythonリストとして適切に情報を取得するのでしょうか?Pythonを使用してSqlLite3からリストを追加および取得する

データを取得する場合、必要に応じて、予想通り、それは文字列のタプルを返し、その後、あなたはast.literal_eval機能が動作するはずです。この特定の場合のために、適切なデータ型では各要素を変換する必要があります
import sqlite3 
import hashlib 


database = 'test.db' 


def create_table(): 
    connection = sqlite3.connect(database) 
    cursor = connection.cursor() 

    cursor.execute("CREATE TABLE IF NOT EXISTS assets(url BLOB UNIQUE, colors BLOB, tags BLOB)") 

    connection.commit() 
    cursor.close() 
    connection.close() 


def kill_table(): 
    connection = sqlite3.connect(database) 
    cursor = connection.cursor() 
    cursor.execute('''DROP TABLE IF EXISTS assets''') 
    connection.commit() 


def read_from_db(): 
    connection = sqlite3.connect(database) 
    cursor = connection.cursor() 

    cursor.execute('SELECT * FROM assets') 
    data = cursor.fetchall() 
    print(len(data)) 
    for row in data: 
     print(row) 

    cursor.close() 
    connection.close() 


def get_data_entry(url=''): 
    connection = sqlite3.connect(database) 
    cursor = connection.cursor() 

    url = hashlib.md5(url).hexdigest() 

    cursor.execute('SELECT * FROM assets WHERE url=?', (url,)) 
    data = cursor.fetchall() 

    if len(data) == 1: 
     return data[0] 
    else: 
     print 'Found multiple entry instances' 
     return False 


def append_data_entries(url, colors, tags): 
    ''' 
    Args: 
     url (str): name of image item 
     colors (list): list of dominant image colors 
     tags (list): list of tags 
    ''' 
    if not url or not colors or not tags: 
     return False 

    url = hashlib.md5(url).hexdigest() 
    colors = str(colors) 
    tags = str(tags) 

    # updates or inserts 
    cursor.execute("REPLACE INTO assets(url, colors, tags) VALUES (?, ?, ?)", 
      (url, colors, tags)) 

    return True 



if __name__ == '__main__': 
    'Example' 
    kill_table() 
    create_table() 

    # add test data to database 
    connection = sqlite3.connect(database) 
    cursor = connection.cursor() 

    for i in range(10): 
     url = '{num:08d}'.format(num=i) 
     append_data_entries(url, '[[0,0,0],[10,10,10],[50,50,50]]','["red","green","blue","orange"]') 

    connection.commit() 
    cursor.close() 
    connection.close() 


    read_from_db() 
    print 'ITEM:', get_data_entry('00000006') 

答えて

1

def convert(in_data): 
    def cvt(data): 
     try: 
      return ast.literal_eval(data) 
     except Exception: 
      return str(data) 
    return tuple(map(cvt, in_data)) 

例コード:

import sqlite3 
import hashlib 
import ast 

database = 'test.db' 


def create_table(): 
    connection = sqlite3.connect(database) 
    cursor = connection.cursor() 

    cursor.execute("CREATE TABLE IF NOT EXISTS assets(url BLOB UNIQUE, colors BLOB, tags BLOB)") 

    connection.commit() 
    cursor.close() 
    connection.close() 


def kill_table(): 
    connection = sqlite3.connect(database) 
    cursor = connection.cursor() 
    cursor.execute('''DROP TABLE IF EXISTS assets''') 
    connection.commit() 

def convert(in_data): 
    def cvt(data): 
     try: 
      return ast.literal_eval(data) 
     except Exception: 
      return str(data) 
    return tuple(map(cvt, in_data)) 

def read_from_db(): 
    connection = sqlite3.connect(database) 
    cursor = connection.cursor() 

    cursor.execute('SELECT * FROM assets') 
    data = cursor.fetchall() 
    print(len(data)) 
    for row in data: 
     print(convert(row)) 

    cursor.close() 
    connection.close() 


def get_data_entry(url=''): 
    connection = sqlite3.connect(database) 
    cursor = connection.cursor() 

    url = hashlib.md5(url).hexdigest() 

    cursor.execute('SELECT * FROM assets WHERE url=?', (url,)) 
    data = cursor.fetchall() 

    if len(data) == 1: 
     return convert(data[0]) 
    else: 
     print('Found multiple entry instances') 
     return False 


def append_data_entries(url, colors, tags): 
    ''' 
    Args: 
     url (str): name of image item 
     colors (list): list of dominant image colors 
     tags (list): list of tags 
    ''' 
    if not url or not colors or not tags: 
     return False 

    url = hashlib.md5(url).hexdigest() 
    colors = str(colors) 
    tags = str(tags) 

    # updates or inserts 
    cursor.execute("REPLACE INTO assets(url, colors, tags) VALUES (?, ?, ?)", 
      (url, colors, tags)) 

    return True 



if __name__ == '__main__': 
    'Example' 
    kill_table() 
    create_table() 

    # add test data to database 
    connection = sqlite3.connect(database) 
    cursor = connection.cursor() 

    for i in range(10): 
     url = '{num:08d}'.format(num=i) 
     append_data_entries(url, '[[0,0,0],[10,10,10],[50,50,50]]','["red","green","blue","orange"]') 

    connection.commit() 
    cursor.close() 
    connection.close() 


    read_from_db() 
    print('ITEM:', get_data_entry('00000006')) 
関連する問題