2

I am trying to import SQL server data in pandas as a dataframe. I currently have the following code:

import pandas as pd
import pyodbc

# SQL Authentication
conn = pyodbc.connect(
        'Driver={SQL Server};'
        'Server=Servername;'
        'Database=DBName;'
        'UID=logIn;'
        'PWD=Password;')
    
cursor = conn.cursor()
    
cursor.execute('SELECT * FROM Table')
    
result = cursor.fetchall()
     
cursor.close()
print(result)

This returns the data, but in the following format:

[(24609189, 'EURTRY.pro', Decimal('5'), Decimal('11'), Decimal('5.0000'), Decimal('105.0000'), Decimal('-2.200000'), Decimal('0.000000'), datetime.datetime(2018, 10, 15, 16, 47, 17, 800000), None)]

How am I able to get this into a dataframe, and is there a way to remove the Decimal in front of the numbers?

1
  • did you try the native pandas method pd.read_sql("SELECT * FROM schema.Table", conn) Commented Mar 12, 2021 at 10:25

1 Answer 1

2

You should be able to do this directly with read_sql() from Pandas:

import pandas as pd
import pyodbc

# SQL Authentication
conn = pyodbc.connect(
        'Driver={SQL Server};'
        'Server=Servername;'
        'Database=DBName;'
        'UID=logIn;'
        'PWD=Password;') 

sql = 'SELECT * FROM Table'
data = pd.read_sql(sql,conn)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.