Pycharm's python code to access MS SQL database

Hi

I can connect to the Microsoft SQL database in pycharm. I can use the console from pycharm to query. But I have no idea how to connect to the database, query and read into pandas dataframe in pycharm. 

Could you provide a sample code?

Thanks

0
2 comments

Hi, you need a python library that supports your specific database. For MS SQL, consider official MS documentation: https://docs.microsoft.com/en-us/sql/connect/python/python-driver-for-sql-server?view=sql-server-ver15

0

It doesn't really seem like a PyCharm question. Have you looked into pyodbc and SQL alchemy?

The following works for me:

 


from sqlalchemy import create_engine, MetaData, Table, select
import sqlalchemy as sqlalchemy


ServerName = ######################
Database = ######################
params = '?driver=SQL+Server+Native+Client+11.0'
engine = create_engine('mssql+pyodbc://' + ServerName + '/'+ Database + params, encoding ='utf_8' )
connection=engine.raw_connection()

df = pd.read_sql('select * from dbo.my_table', connection)
my_dataframe.to_sql(t.outp, engine, schema='dbo', if_exists='replace', index=False)

0

Please sign in to leave a comment.