python连接sqlite数据库源码
import sqlite3
def create_connection(db_file):""" 创建数据库连接 """conn = Nonetry:conn = sqlite3.connect(db_file)return connexcept sqlite3.Error as e:print(e)return conn
def create_table(conn):""" 创建表 """try:cursor = conn.cursor()cursor.execute('''CREATE TABLE IF NOT EXISTS sheet1(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')except sqlite3.Error as e:print(e)def select_all_users(conn):""" 查询所有用户 """global llllll=[]try:cursor = conn.cursor()cursor.execute("SELECT * FROM Sheet1")headers = [header[0] for header in cursor.description]rows = cursor.fetchall()for row in rows:lll.append(row)except sqlite3.Error as e:print(e)
def main():database = "st_score.db"conn = create_connection(database)if conn is not None:create_table(conn)print("查询到的所有用户:")select_all_users(conn)conn.close()else:print("Error! 无法创建数据库连接。")if __name__ == '__main__':main()for i, row in enumerate(lll):print(row)for j,item in enumerate(row):print(i,j,item)