将二维数组信息,邪恶如数据库,如果没有数据库就自动创建数据库;sqlist3数据库
import os
import sqlite3
def write_to_sqlite(data, db_filename, table_name, headers):
'''
将二维数组信息,邪恶如数据库,如果没有数据库就自动创建数据库;
:param data: #要写入的二维数组
:param db_filename: 数据库名字
:param table_name: 数据库表明名
:param headers: 一维数组,数据库表头
:return:
'''
db_filename=db_filename+'.db'
if not os.path.exists(db_filename):
open(db_filename, 'w').close()
conn = sqlite3.connect(db_filename)
c = conn.cursor()
c.execute(f"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{table_name}'")
if c.fetchone()[0] == 0:
create_sql = f"CREATE TABLE {table_name} ({','.join([f'{header} TEXT' for header in headers])})"
c.execute(create_sql)
placeholders = ",".join(["?" for _ in range(len(headers))])
insert_sql = f"INSERT INTO {table_name} ({','.join(headers)}) VALUES ({placeholders})"
for row in data:
c.execute(insert_sql, row)
conn.commit()
conn.close()
python 读取sqlist3返回二维数组
def read_sqlist(table_name,db_filename):
'''
从指定表明中 读取sqlist,返回二维数组
:param table_name:
:param db_filename:
:return:
'''
db_filename = db_filename + '.db'
conn = sqlite3.connect(db_filename)
dataFrame = pd.read_sql('select * from %s'%table_name, conn)
print(dataFrame)
arr_data=dataFrame.values
arr_data=arr_data.tolist()
print(arr_data)
return arr_data
删除sqlist3中的所有数据
def delsqlist(db_file = 'main.db',table_name="table_name"):
'''
删除表 中的所有数据
:param db_file:
:param table_name:
:return:
'''
conn = sqlite3.connect(db_file)
conn.execute('DELETE FROM %s'%table_name)
conn.commit()
conn.close()