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)
现在,我看起来不错,但我遇到了编程错误
编程错误:('42000',“[42000] [Microsoft][ODBC SQL Server 驱动程序][SQL Server]关键字“if”附近的语法不正确。(156) (SQLExecDirectW); [42000] [Microsoft][ ODBC SQL Server 驱动程序][SQL Server]在“客户”附近预期条件的上下文中指定的非 bool 类型表达式。(4145)
Visit https://www.dofactory.com/sql/sample-database
查看我正在处理的数据库结构。
再次感谢
最佳答案
Microsoft SQL Server 2016 中引入了对 DROP TABLE IF EXISTS ...
的支持。显然您使用的是早期版本的 SQL Server,因此您必须使用解决方法。请参阅this question了解详情。
关于python - 将数据从数据库移动到另一个数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122381/