我不确定该怎么称呼,随时可以编辑我的帖子标题。
在我开始之前,我用谷歌搜索了here,但这似乎没有帮助。
我的代码:
import pyodbc
import pandas as pd
import numpy as np
import os
import sqlalchemy as sal
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import Table, Column, Integer, Numeric, String, ForeignKey, Boolean
##
from datetime import datetime
from sqlalchemy import DateTime
from sqlalchemy import PrimaryKeyConstraint, UniqueConstraint, CheckConstraint
from sqlalchemy import Index
from sqlalchemy import ForeignKeyConstraint
from sqlalchemy import insert
from sqlalchemy.sql import select
from sqlalchemy.sql import func
from sqlalchemy import cast
from sqlalchemy import and_, or_, not_
from sqlalchemy import update, delete
from sqlalchemy import text
##
import urllib
#############################################################
server = 'fake_server'
database = '_Testing_Only'
driver = 'SQL+SERVER+NATIVE+CLIENT+11.0'
trusted_connection='yes'
database_connection = 'mssql+pyodbc://fake_server/' + database + '?trusted_connection=' + trusted_connection + '&driver=' + driver
engine = sal.create_engine(database_connection)
connection=engine.connect()
metadata = MetaData()
print(engine.table_names())
这是我的打印声明的结果:
['cookies', 'line_items', 'orders', 'testing_sym_keys', 'users']
然后我尝试运行以下代码:
s = select([cookies])
我收到以下错误消息:
Traceback (most recent call last):
File "<pyshell#167>", line 1, in <module>
s = select([cookies])
NameError: name 'cookies' is not defined
该表显然存在,为什么我会收到错误消息?
答案 0 :(得分:1)
问题是您没有将引擎变量中的表绑定到Python代码中的变量。
尝试运行以下形式的本机SQL查询:
engine = create_engine(database_connection)
metadata = MetaData(engine)
metadata.reflect()
with engine.begin() as conn:
conn.execute("select * from cookies")
其他解决方案,如果要使用选择方法,则可以尝试以下方法:
engine = create_engine(database_connection)
meta = MetaData(engine).reflect()
table = meta.tables['cookies']
# select * from 'cookies'
select_cookies = select([table])
答案 1 :(得分:0)
刚刚为此找到了一个快速解决方案。首先尝试为您想要的表创建表对象。
engine = create_engine(database_connection)
metadata = MetaData()
cookies = Table('cookies', metadata, autoload=True, autoload_with=engine)
所以每次你想查询一个表时,只要每一个都执行上面的代码,这样你就可以在python中初始化该表。