将数据从数据库移动到另一个数据库时出错

时间:2019-05-14 02:54:14

标签: python sqlalchemy etl pyodbc petl

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驱动程序] [SQL Server]”关键字“ if”附近的语法不正确。(156)(SQLExecDirectW); [42000] [Microsoft] [ ODBC SQL Server驱动程序] [SQL Server]在“ Customer”附近需要条件的上下文中指定的非布尔类型的表达式。(4145)

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

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

再次感谢您

1 个答案:

答案 0 :(得分:0)

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