【问题标题】:Importing .db file into Postgresql database将 .db 文件导入 Postgresql 数据库
【发布时间】:2019-10-05 09:52:39
【问题描述】:

我目前正在编写一个脚本来将 .db 文件导入 Postgresql 数据库,包括数据。有没有什么方法可以在不使用第三方工具和使用 python 的情况下做到这一点?

【问题讨论】:

  • .db 甚至不是定义的文件格式。
  • 对不起,我应该改写这个问题。所以我有一个已经创建的 sqlite 数据库。我想将它导入到 postgresql。有没有办法使用 python 来做这些事情?

标签: python sql postgresql sqlite


【解决方案1】:

你肯定可以用 Django 做到这一点。

  • python manage.py dumpdata > db.json
  • 将数据库设置更改为新数据库,例如 PostgreSQL。
  • python manage.py 迁移
  • python manage.py shell
  • 在shell中输入以下内容
from django.contrib.contenttypes.models import ContentType
ContentType.objects.all().delete()
  • python manage.py loaddata db.json

否则,如果您想修改自己的方式。 你需要安装 psycopg2

$ pip install psycopg2

然后你连接到 Postgres。

import psycopg2
conn = psycopg2.connect("host=localhost dbname=postgres user=postgres")

这是插入值的方式。

cur = conn.cursor()
insert_query = "INSERT INTO users VALUES {}".format("(10, 'hello@dataquest.io', 'Some Name', '123 Fake St.')")
cur.execute(insert_query)
conn.commit()

现在使用 SQLAlchemy,您可以轻松打开 SQLite 文件。

import sqlite3
conn = sqlite3.connect('database.db')

获取数据。

r = conn.execute("""SELECT * FROM books""")
r.fetchall()

这是从 SQLite 获取所有表的方法

数据库中的所有表名:

SELECT name FROM sqlite_master WHERE type = 'table'

sqlite_master 可以被认为是一个包含数据库信息(元数据)的表。

一种快速但很可能效率低下的方法(因为它将运行 700 个查询和 700 个单独的结果集)来获取表名列表,遍历这些表并返回数据 where columnA = "-":

for row in connection.execute('SELECT name FROM sqlite_master WHERE type = "table" ORDER BY name').fetchall()
    for result in connection.execute('SELECT * FROM ' + row[1] + ' WHERE "columnA" = "-"').fetchall()
    # do something with results

这是另一种方法

import sqlite3
try:
    conn = sqlite3.connect('/home/rolf/my.db')
except sqlite3.Error as e:
    print('Db Not found', str(e))
db_list = []
mycursor = conn.cursor()
for db_name in mycursor.execute("SELECT name FROM sqlite_master WHERE type = 'table'"):
    db_list.append(db_name)
for x in db_list:
    print "Searching",x[0]
    try:
        mycursor.execute('SELECT * FROM '+x[0]+' WHERE columnA" = "-"')
        stats = mycursor.fetchall()
        for stat in stats:
            print stat, "found in ", x
    except sqlite3.Error as e:
       continue
conn.close()

【讨论】:

  • 谢谢!但是如何遍历具有多个表的数据库,从而通过获取它们的table_name 使其更通用?
  • 我认为导入db-files有一个特殊的查询...我目前正在搜索...
  • 对于 sqlite 它的附加,但对于 postgresql pgloader 应该是解决方案。也可以通过 csv 文件,但是你没有机会保留外键......
猜你喜欢
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 2018-05-02
  • 2016-08-23
  • 2012-10-20
  • 2018-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多