Answer a question

I can successfully query and insert data using sqlalchemy and pandas:

from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('mssql://myserver/mydb?driver=SQL+Server+Native+Client+11.0?trusted_connection=yes')

Read tempy table:

sql_command = """
select top 100 * from tempy
"""

df = pd.read_sql(sql_command, engine)
print df

   tempID  tempValue
0       1          2

Append new data:

df_append = pd.DataFrame( [[4,6]] , columns=['tempID','tempValue']) 
df_append.to_sql(name='tempy', con=engine, if_exists = 'append', index=False)

df = pd.read_sql(sql_command, engine)
print df

   tempID  tempValue
0       1          2
1       4          6

Try to truncate data:

connection = engine.connect()
connection.execute( '''TRUNCATE TABLE tempy''' )
connection.close()

Read table again, but truncate failed:

df = pd.read_sql(sql_command, engine)
print df

   tempID  tempValue
0       1          2
1       4          6

Answers

This worked for me:

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
session.execute('''TRUNCATE TABLE tempy''')
session.commit()
session.close()
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐