Connecting to Microsoft SQL Server using Python

Hello All,

Here is a quick guide to connect to Microsoft SQL Server and Extract data to a csv. I have an interest in python recently and posting all that saves me time at work. Python is so powerful that it saves me a lot of time either doing the work manually or writing the same process using other tools.

The code below is simple , first it connects to microsoft sql server and then saves the code as a dataframe which is later written into csv.

 

Cheers !!

Code

@author: Jethin.Abraham
"""

import pandas as pd
import pyodbc




cnxn =pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};Server=Server Name ;Database=Schema;uid=userid;pwd=password")
df = pd.read_sql_query('''select TOP 10 * from table name''', cnxn)
df.to_csv("C:\\Users\\Jethin.Abraham\\Documents\\python_test.csv")

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s