如何解决如何使用 pyodbc 将表从 MS Access 迁移到 Postgres?
我需要将表格从 MS Access 迁移到 Postgres。我想使用 pyodbc 来执行此操作,因为它允许我使用 python 连接到 Access 数据库并查询数据。
我遇到的问题是我不完全确定如何以编程方式创建具有相同架构的表,而不仅仅是使用字符串格式创建 sql 语句。 pyodbc 提供了列出所有字段、字段类型和字段长度的能力,因此我可以创建一个包含所有相关信息的长 sql 语句,但是如何为一堆表执行此操作?我是否需要为每个表构建 sql 字符串语句?
import pyodbc
access_conn_str = (r'DRIVER={Microsoft Access Driver (*.mdb,*.accdb)}; 'r'DBQ=C:\Users\bob\access_database.accdb;')
access_conn = pyodbc.connect(access_conn_str)
access_cursor = access_conn.cursor()
postgres_conn_str = ("DRIVER={Postgresql Unicode};""DATABASE=access_database;""UID=user;""PWD=password;""SERVER=localhost;""PORT=5433;")
postgres_conn = pyodbc.connect(postgres_conn_str)
postgres_cursor = postgres_conn.cursor()
table_ditc = {}
row_dict = {}
for row in access_cursor.columns(table='table1'):
row_dict[row.column_name] = [row.type_name,row.column_size]
table_ditc['table1'] = row_dict
for table,values in table_ditc.items():
print(f"Creating table for {table}")
access_cursor.execute(f'SELECT * FROM {table}')
result = access_cursor.fetchall()
postgres_cursor.execute(f'''CREATE TABLE {table} (Do I just put a bunch of string formatting in here?);''')
postgres_cursor.executemany(f'INSERT INTO {table} (Do I just put a bunch of string formatting) VALUES (string formatting?)',result)
postgres_conn.commit()
如您所见,使用 pyodbc 我不确定如何构建 sql 语句。我知道我可以手动构建一个长字符串,但是如果我要制作一堆不同的表格,具有不同的字段等,那将是不现实的。是否有更好、更简单的方法来基于 Access 数据库的架构创建表和插入行?
解决方法
我最终使用了 const MyForm = ({ subjects }) => {
// removed initial values for subjects
// you could set these,but they aren't required
const [state,setState] = useState({
name: "",email: "",message: "",emailSent: false
});
// no changes to this function
const onInputChange = (e) => {
const item = e.target.name;
const value =
e.target.type === "checkbox" ? e.target.checked : e.target.value;
setState({
...state,[item]: value
});
};
return (
<form>
<input
id="name"
type="text"
value={state.name}
onChange={onInputChange}
name="name"
required
/>
{/* ... other inputs ... */}
{subjects.map((subject,i) => (
<div className="w-full sm:w-auto" key={i}>
<label className="flex content-center p-3">
<input
type="checkbox"
name={subject.name}
value={subject.name}
onChange={onInputChange}
checked={!!state[subject.name]}
/>
<span className="ml-3">{subject.label}</span>
</label>
</div>
))}
</form>
);
};
和 pyodbc
的组合。 pywin32
“基本上是一个非常薄的 Python 包装器,它允许我们与 COM 对象交互并使用 Python 自动化 Windows 应用程序”(引自下面的第二个链接)。
我能够以编程方式与 Access 交互,并使用 pywin32
https://docs.microsoft.com/en-us/office/vba/api/access.docmd.transferdatabase https://pbpython.com/windows-com.html
DoCmd.TransferDatabase
这种方法似乎对我有用。我喜欢表/字段的创建以及数据的插入都是自动处理的(这是我在使用 import win32com.client
import pyodbc
import logging
from pathlib import Path
conn_str = (r'DRIVER={Microsoft Access Driver (*.mdb,*.accdb)}; 'rf'DBQ={access_database_location};')
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
a = win32com.client.Dispatch("Access.Application")
a.OpenCurrentDatabase(access_database_location)
table_list = []
for table_info in cursor.tables(tableType='TABLE'):
table_list.append(table_info.table_name)
for table in table_list:
logging.info(f"Exporting: {table}")
acExport = 1
acTable = 0
db_name = Path(access_database_location).stem.lower()
a.DoCmd.TransferDatabase(acExport,"ODBC Database","ODBC;DRIVER={PostgreSQL Unicode};"f"DATABASE={db_name};"f"UID={pg_user};"f"PWD={pg_pwd};""SERVER=localhost;"f"PORT={pg_port};",acTable,f"{table}",f"{table.lower()}_export_from_access")
logging.info(f"Finished Export of Table: {table}")
logging.info("Creating empty table in EGDB based off of this")
时遇到的原始问题)。
如果有人有更好的方法,我愿意接受建议。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。