1

我正在尝试通过 Python 为 Snowflake 生成多个文件表结构

我在目录中有文件列表,我想从文件中读取数据,使用文件名在雪花中动态创建表。

以下是我到目前为止尝试过的

# Generate Multiple files Table Structure to Snowflake via Python
import os
from os import path
import pandas as pd
import snowflake.connector
from snowflake.sqlalchemy import URL
from sqlalchemy import create_engine
from snowflake.connector.pandas_tools import write_pandas, pd_writer

dir = r"D:\Datasets\users_dataset"

engine = create_engine(URL(
    account='<account>',
    user='<user>',
    password='<password>',
    role='ACCOUNTADMIN',
    warehouse='COMPUTE_WH',
    database='DEM0_DB',
    schema='PUBLIC'
))

connection = engine.connect()
connection.execute("USE DATABASE DEMO_DB")
connection.execute("USE SCHEMA PUBLIC")
results = connection.execute('USE DATABASE DEMO_DB').fetchone()
print(results)
# read the files from the directory and split the filename and extension

for file in os.listdir(dir):
    name, extr = path.splitext(file)
    print(name)
    file_path = os.path.join(dir, file)
    print(file_path)
    df = pd.read_csv(file_path, delimiter=',')
    df.to_sql(name, con=engine, index=False)

我得到以下错误

sqlalchemy.exc.ProgrammingError: (snowflake.connector.errors.ProgrammingError) 090105 (22000): Cannot perform CREATE TABLE. This session does not have a current database. Call 'USE DATABASE', or use a qualified name.
[SQL: 
CREATE TABLE desktop (
    "[.ShellClassInfo]" FLOAT
)

]
(Background on this error at: https://sqlalche.me/e/14/f405)

我检查了雪花的权限问题,没有发现任何问题。

有人可以帮忙解决这个错误吗

4

1 回答 1

0

在 create_engine 调用数据库DEM0_DB而不是DEMO_DB

engine = create_engine(URL(
    ...
    #database='DEM0_DB',
    database='DEMO_DB',
    schema='PUBLIC'
))
于 2021-12-11T20:53:04.153 回答