如何从 sqlalchemy 连接到 sqlite

Ste*_*hen 9 python sqlite sqlalchemy

我的主目录中有一个 sqlite 数据库。

stephen@stephen-AO725:~$ pwd
/home/stephen
stephen@stephen-AO725:~$ sqlite db1
SQLite version 2.8.17
Enter ".help" for instructions
sqlite> select * from test
   ...> ;
3|4
5|6
sqlite> .quit
Run Code Online (Sandbox Code Playgroud)

当我尝试从 jupiter 笔记本与 sqlalchemy 和 pandas 连接时,某些东西不起作用。

db=sqla.create_engine('sqlite:////home/stephen/db1')
pd.read_sql('select * from db1.test',db)
Run Code Online (Sandbox Code Playgroud)

〜/anaconda3/lib/python3.7/site-packages/sqlalchemy/engine/default.py in do_execute(自我,光标,语句,参数,上下文)578 579 def do_execute(自我,光标,语句,参数,上下文=无): --> 580 游标.execute(语句, 参数) 581 582 def do_execute_no_params(self, 游标, 语句, context=None):

DatabaseError: (sqlite3.DatabaseError) 文件不是数据库 [SQL: select * from db1.test] (此错误的背景位于: http: //sqlalche.me/e/4xp6

我也尝试过:

db=sqla.create_engine('sqlite:///~/db1')
Run Code Online (Sandbox Code Playgroud)

相同的结果

Cor*_*oca 14

就个人而言,只需用所需的模块来完成@Stephen的代码:

# 1.-Load module
import sqlalchemy
import pandas as pd
#2.-Turn on database engine
dbEngine=sqlalchemy.create_engine('sqlite:////home/stephen/db1.db') # ensure this is the correct path for the sqlite file. 

#3.- Read data with pandas
pd.read_sql('select * from test',dbEngine)

#4.- I also want to add a new table from a dataframe in sqlite (a small one) 

df_todb.to_sql(name = 'newTable',con= dbEngine, index=False, if_exists='replace') 

Run Code Online (Sandbox Code Playgroud)

另一种阅读方法是使用 sqlite3 库,这可能更直接:

#1. - Load libraries
import sqlite3
import pandas as pd

# 2.- Create your connection.
cnx = sqlite3.connect('sqlite:////home/stephen/db1.db')
cursor = cnx.cursor()

# 3.- Query and print all the tables in the database engine
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())

# 4.-  READ TABLE OF SQLITE CALLED test
dfN_check = pd.read_sql_query("SELECT * FROM test", cnx) # we need real name of table

#  5.- Now I want to delete all rows of this table
cnx.execute("DELETE FROM test;")

# 6. -COMMIT CHANGES! (mandatory if you want to save these changes in the database)
cnx.commit()


# 7.- Close the connection with the database
cnx.close()
Run Code Online (Sandbox Code Playgroud)

请让我知道这可不可以帮你!


小智 6

import sqlalchemy

engine=sqlalchemy.create_engine(f'sqlite:///db1.db')
Run Code Online (Sandbox Code Playgroud)

注意:您需要三个斜杠sqlite:///才能使用数据库的相对路径。
如果您想要绝对路径,请使用四个斜杠:sqlite://// 来源:链接


Ste*_*hen 2

正如 Everila 所指出的,问题在于没有向后兼容性。anaconda安装了自己的sqlite,即sqlite3.x,并且在使用sqlite 3创建数据库后,sqlite无法加载由sqlite 2.x创建的数据库代码工作正常

db=sqla.create_engine('sqlite:////home/stephen/db1')
pd.read_sql('select * from test',db)
Run Code Online (Sandbox Code Playgroud)

这确认需要 4 个斜杠。