1

python上的ETL代码错误

我设法在 python 上学习了一些代码行,以便在 MS SQL 环境中执行 ETL 过程。初始脚本用于 PostgreSQL 环境。我想将我的用于 MS SQL。我尝试编辑代码,但出现错误。请看一看

import petl as etl, pyodbc as py, sys
from sqlalchemy import *

reload(sys)
sys.setdefaultencoding('utf8')

dbCnxns = {'sample' :"dbname=sample user=user host=127.0.0.1" 
           , 'python': "dbname=python user=user host=127.0.0.1" }

#set my connection
sourceConn = py.connect(dbCnxns['sample'])
targetConn = py.connect(dbCnxns['python'])
sourceCursor = sourceConn.cursor()
targetCursor = targetConn.cursor()

sourceCursor.execute = ('SELECT name from sys.tables')


sourceTables = sourceCursor.fetchall()

for t in sourceTables:
    targetCursor.execute("drop table if exist %s" % (t[0]))
    sourceDs = etl.fromdb(sourceConn, "select * from %s" % (t[0]))
    etl.todb(sourceDs,targetConn,t[0], create=True, sample=1000)

谢谢

经过一些修改。我能够为 MSSQL D 编写代码。这是之前的代码

import petl as etl, pyodbc as py
#from sqlalchemy import *

#reload(sys)
#sys.setdefaultencoding('utf8')

#dbCnxns = {'sample' : "Driver={SQL Server} Server=USER-PC Database=sample Trusted_Connection=yes" 
#           , 'python': "Driver={SQL Server} Server=USER-PC Database=python Trusted_Connection=yes" }

#set my connection
#sourceConn = pg.connect(dbCnxns['sample'])
#targetConn = pg.connect(dbCnxns['python'])
#sourceCursor = sourceConn.cursor()
#targetCursor = targetConn.cursor()

#sourceCursor.execute = (***SELECT * FROM sample.dbo.Customer***)


sourceConn = py.connect('Driver={SQL Server};'
                      'Server=USER-PC;'
                      'Database=sample;'
                      'Trusted_Connection=yes;')

targetConn = py.connect('Driver={SQL Server};'
                      'Server=USER-PC;'
                      'Database=python;'
                      'Trusted_Connection=yes;')

sourceCursor = sourceConn.cursor()
targetCursor = targetConn.cursor()

sourceCursor.execute('SELECT name from sys.tables')

sourceTables = sourceCursor.fetchall()

for t in sourceTables:
    targetCursor.execute("drop table if exist %s" % (t[0]))
    sourceDs = etl.fromdb(sourceConn, "select * from %s" % (t[0]))
    etl.todb(sourceDs,targetConn,t[0], create=True, sample=1000)

现在,我看起来不错,但是我遇到了编程错误

ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]关键字'if'附近的语法不正确。(156) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server驱动程序][SQL Server]在“客户”附近的预期条件的上下文中指定的非布尔类型表达式。(4145)

Visit https://www.dofactory.com/sql/sample-database

查看我正在处理的数据库结构。

再次感谢你

4

1 回答 1

1

Microsoft SQL Server 2016 中引入了对 的支持DROP TABLE IF EXISTS ...。您显然使用的是 SQL Server 的早期版本,因此您必须使用解决方法。有关详细信息,请参阅此问题

于 2019-05-15T14:22:15.533 回答