本地搭建Python和SQLite数据交互环境

1. SQLite安装:

在 Windows 上安装 SQLite

请访问 SQLite下载页面,从 Windows 区下载预编译的二进制文件。

您需要下载 sqlite-tools-win32-.zip 和 sqlite-dll-win32-.zip 压缩文件。

创建文件夹C:\sqlite,并在此文件夹下解压上面两个压缩文件,将得到 sqlite3.def、sqlite3.dll 和 sqlite3.exe 文件。

添加C:\sqlite 到 PATH 环境变量,最后在命令提示符下,使用 sqlite3 命令,将显示如下结果。


C:\>sqlite3

SQLite version 3.7.15.2 2013-01-09 11:53:05

Enter ".help" for instructions

Enter SQL statements terminated with a ";"

sqlite>

便捷查看表的软件。
Navicat for sqlite安装

2. python与sqlite的交互

  1. 通过cursor访问

conn = sqlite3.connect('stock.db')

print("Opened database successfully")

c = conn.cursor()
#c.execute('''CREATE TABLE COMPANY
#       (ID INT PRIMARY KEY     NOT NULL,
#       NAME           TEXT    NOT NULL,
#       AGE            INT     NOT NULL,
#       ADDRESS        CHAR(50),
#       SALARY         REAL);''')
#print("Table created successfully")
#conn.commit()
#conn.close()


c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
      VALUES (1, 'Paul', 32, 'California', 20000.00 )");

c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
      VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");

c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
      VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");

c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
      VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");

conn.commit()
print("Records created successfully")
conn.close()

c = conn.cursor()
cursor = c.execute("SELECT id, name, address, salary  from COMPANY")

#for row in cursor:
#   print("ID = ", row[0])
#   print("NAME = ", row[1])
#   print("ADDRESS = ", row[2])
#   print("SALARY = ", row[3], "\n")

results = cursor.fetchall()
print(results)

c.close()
conn.close()
  1. pandas读取和写入,自定义函数。
# some database functions
def df_read_all(db, tb):
    conn = sqlite3.connect(db) 
    print("Opened database successfully")
    df = pd.read_sql_query("select * from {};".format(tb), conn)
    print("Read tables completed")
    conn.close()
    return df
    
def df_write_all(db, tb, df, way='replace'):
    conn = sqlite3.connect(db) 
    print("Opened database successfully")
    df.to_sql(tb, con=conn, if_exists=way, index=False)
    print("Write tables completed")
#    df1 = pd.read_sql_query("select * from {};".format(tb), conn)
#    print(df1)
    conn.close()
    return

df = pd.DataFrame({'df' : ['User dfasd', 'User dfd', 'User 3']})
df_write_all(db='stock.db', tb='user', df=data)
df1 = df_read_all(db='stock.db', tb='user')

3. 几个参考网址

markdown 使用方法
sqlite简单使用
python sqlite3 包
pandas 访问sqlite简介1
pandas 访问sqlite简介2

你可能感兴趣的:(本地搭建Python和SQLite数据交互环境)