1

I have connected to a SQL database through python and am trying to extract one column of data. However, when I go to print what I extracted, it displays the following:

('A', )
('B', )
('C', )
('D', )

When I extract two columns, it prints:

('A', 'a' )
('B', 'b')
('C', 'c')
('D', 'd')

Is there a way to simply take the data in the first column without the additional , ) or even transform into a dataframe while preserving the column names from SQL? I have found a lot of guides how to extract data from SQL, but none showing ability to operate as a dataframe and preserve column names.

Code to generate:

import pyodbc
conn = pyodbc.connect(driver='{SQL Server}'
                      ,server = 'server'
                      ,database = 'db1'
                      ,trusted_connection=True
                      ,user='user')
cursor=conn.cursor()
cursor.execute(
        '''SELECT
                Column_One
                --,Column_Two
            FROM db1.table''')
for row in cursor.fetchall():
    print(row)

2 Answers 2

2

Try that

import pyodbc
conn = pyodbc.connect(driver='{SQL Server}'
                      ,server = 'server'
                      ,database = 'db1'
                      ,trusted_connection=True
                      ,user='user')
cursor=conn.cursor()
cursor.execute(
        '''SELECT
                Column_One
                --,Column_Two
            FROM db1.table''')

final_result = [list(i) for i in cursor.fetchall()]
Sign up to request clarification or add additional context in comments.

1 Comment

This prints a list of lists such that each inner list is 1 element. It works for my simple tasks, but does not preserve the columns. Very simplistic for small stuff like I need now.
0
from sqlalchemy import create_engine
import pymysql
def keyword_sql():
    try:
        db_connection_str = 'mysql+pymysql://user:password@server/database'
        db_connection = create_engine(db_connection_str)
        df = pd.read_sql('SELECT keyword, category FROM additional_data_dictionary', con=db_connection)
        return df
    except:
        print("mysql connection issue - ignoring the user input")
        sys.exit(1)

See if this helps, I am not using pyodbc, I am using "sqlalchemy" - this code directly returns the pandas dataframe

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.