简体   繁体   中英

How to execute pure SQL query in Python

I am trying to just create a temporary table in my SQL database, where I then want to insert data (from a Pandas DataFrame ), and via this temporary table insert the data into a 'permanent' table within the database.

So far I have something like

""" Database specific... """

import sqlalchemy
from sqlalchemy.sql import text

dsn = 'dsn-sql-acc'
database = "MY_DATABASE"

connection_str =    """
                            Driver={SQL Server Native Client 11.0};
                            Server=%s;
                            Database=%s;
                            Trusted_Connection=yes;
                    """ % (dsn,database)

connection_str_url = urllib.quote_plus(connection_str)
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % connection_str_url, encoding='utf8', echo=True)

# Open connection

db_connection = engine.connect()

sql_create_table = text("""          
                            IF OBJECT_ID('[MY_DATABASE].[SCHEMA_1].[TEMP_TABLE]', 'U') IS NOT NULL
                            DROP TABLE [MY_DATABASE].[SCHEMA_1].[TEMP_TABLE];

                            CREATE TABLE [MY_DATABASE].[SCHEMA_1].[TEMP_TABLE] (
                                [Date] Date,
                                [TYPE_ID] nvarchar(50),
                                [VALUE] nvarchar(50)
                                );


                     """)

db_connection.execute("commit")                  
db_connection.execute(sql_create_table)

db_connection.close()

The "raw" SQL-snippet within sql_create_table works fine when executed in SQL Server, but when running the above in Python, nothing happens in my database...

What seems to be the issue here?

Later on I would of course want to execute

BULK INSERT [MY_DATABASE].[SCHEMA_1].[TEMP_TABLE]
FROM '//temp_files/temp_file_data.csv'
WITH (FIRSTROW = 2,  FIELDTERMINATOR = ',', ROWTERMINATOR='\n');

in Python as well...

Thanks

These statements are out of order:

db_connection.execute("commit")                  
db_connection.execute(sql_create_table)

Commit after creating your table and your table will persist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM