使用sqlalchemy,pyodbc

时间:2016-05-31 15:47:53

标签: python pandas sqlalchemy pyodbc

cnx=sqlalchemy.create_engine("mssql+pyodbc://Omnius:MainBrain1@172.31.163.135:1433/Basis?driver=/opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0")
cnx1 = pyodbc.connect('driver=/opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0;server=SRVWUDEN0835;database=Basis;uid=Omnius; pwd=MainBrain1')
sqlquery = "select top 10 TXN_KEY,SEND_AGENT,PAY_AGENT from Pretty_Txns"
cursor = cnx1.cursor()
df = pd.read_sql(sqlquery,cnx)
model_columns = df.columns.tolist()
 db_columns  = cursor.execute("select TXN_KEY,SEND_AGENT from result").fetchall()
 columns = [column[0] for column in cursor.description]
  to_create =list(set(model_columns) -set(columns))
  for c in to_create:
        a = df[c]
        sql = DDL('ALTER TABLE %s ADD column %s  %s' % (result,a,String(9)))
         cnx.execute(sql)

sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near the keyword 'column'. (156) (SQLExecDirectW)") [SQL: u"ALTER TABLE result ADD column ['API352676', 'AED002782', 'ACB020203', 'ASE094882', 'AII071196', 'AHX012817', 'AED000438', 'AEL051943', 'ADJ031448', 'APM033226']  VARCHAR(9)"]

上面的代码显示了如何使用sqlalchemy和pyodbc将新列添加到数据库中的表。大多数情况下它工作正常但在最后一步失败。

1 个答案:

答案 0 :(得分:3)

您错误地构建了alter table ... add column ... SQL。

它应如下所示(对于单列):

ALTER TABLE table_name ADD COLUMN column_name data_type(precision);

或多列:

ALTER TABLE table_name ADD COLUMN (column1_name data_type(precision), column2_name data_type(precision), column3_name data_type(precision));

我建议在一个命令中添加所有列,因为它可能会短时间锁定字典结构。我还建议你不要在应用程序中这样做,但如果可能的话,手动执行一次。如果不可能/适用,您可以按如下方式更改代码:

'ALTER TABLE {} ADD column ({})'.format(result, ', '.join(['{} {}'.format(c, String(9)) for c in to_create]))