[英]Extract 1 Column of data from SQL in Python
I have connected to a SQL database through python and am trying to extract one column of data.我已通过 python 连接到 SQL 数据库,并试图提取一列数据。 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?有没有办法简单地获取第一列中的数据而无需额外的, )
甚至转换为数据帧,同时保留 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.我找到了很多如何从 SQL 中提取数据的指南,但没有一个显示能够作为数据框进行操作并保留列名。
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)
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()]
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看看这是否有帮助,我没有使用 pyodbc,我使用的是“sqlalchemy”——这段代码直接返回了熊猫数据帧
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.