简体   繁体   English

如何用sqlite3存储二维数组?

[英]How to store two dimensional array with sqlite3?

I have a problem.我有个问题。 I need to store 2d array with sqlite3.我需要用 sqlite3 存储二维数组。 How is it possible.这怎么可能。 I know that 1d array could be converted into string and stored like that, but with 2d array it would be quite complicated.我知道可以将一维数组转换为字符串并像这样存储,但是对于二维数组,它会非常复杂。 I am taking data from excel and using them in matplotlib.我正在从 excel 中获取数据并在 matplotlib 中使用它们。

[['', 6.0, 8.0, 10.0, 12.0, 14.0], ['IB=4', 0.143, 0.146, 0.152, 0.158, 0.167], ['IB=8', 0.415, 0.425, 0.43, 0.44, 0.45], ['IB=10', 0.545, 0.555, 0.57, 0.58, 0.59], ['IB=12', 0.766, 0.778, 0.79, 0.81, 0.83]]

Here's a simple example that saves arbitrary Python objects (by pickle ing them) into two-column tables in SQLite databases.这是一个简单的示例,它将任意 Python 对象(通过 它们进行pickle处理)保存到 SQLite 数据库中的两列表中。

If you have a more complex use case, you can probably adapt this.如果您有更复杂的用例,您可能可以调整它。

import sqlite3
import pickle

DEFAULT_TABLE = "arrays"


def save_blob(db, name, data, table_name=DEFAULT_TABLE):
    pickled_data = pickle.dumps(data, protocol=pickle.HIGHEST_PROTOCOL)
    db.execute(
        f"INSERT INTO {table_name} (name, data) VALUES (?, ?) ON CONFLICT DO UPDATE SET data=data",
        (name, pickled_data),
    )


def load_blob(db, name, table_name=DEFAULT_TABLE):
    res = db.execute(f"SELECT data FROM {table_name} WHERE name = ?", (name,))
    row = res.fetchone()
    if not row:
        raise KeyError(name)
    return pickle.loads(row[0])


def create_blob_table(db, table_name=DEFAULT_TABLE):
    db.execute(
        f"CREATE TABLE IF NOT EXISTS {table_name} (name TEXT PRIMARY KEY NOT NULL, data BINARY NOT NULL)"
    )


def main():
    data = [
        ["", 6.0, 8.0, 10.0, 12.0, 14.0],
        ["IB=4", 0.143, 0.146, 0.152, 0.158, 0.167],
        ["IB=8", 0.415, 0.425, 0.43, 0.44, 0.45],
        ["IB=10", 0.545, 0.555, 0.57, 0.58, 0.59],
        ["IB=12", 0.766, 0.778, 0.79, 0.81, 0.83],
    ]

    db = sqlite3.connect("./db.sqlite3")
    create_blob_table(db, DEFAULT_TABLE)
    save_blob(db, "thing1", data)
    db.commit()  # Remember to commit changes after saving things.
    data2 = load_blob(db, "thing1")
    print(data == data2)


if __name__ == "__main__":
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM