如何通过列名从 SQLAlchemy 实例中获取值?
在本文中,我们将讨论如何借助Python中的 SQLAlchemy 从 SQL 中的表中获取值。
使用的数据库:
安装
pip install SQLAlchemy pymysql
注意: pymysql 是 sqlalchemy 的一个依赖,用户需要安装它才能运行我们的程序。
按列名获取值
可以通过首先使用sqlalchemy创建引擎、连接数据库并使用连接执行 SQL 查询来执行给定的任务。 SQL 查询将包含我们想要其值的列/列的名称,然后我们将获得一个结果对象。当我们调用对象实例的fetchall方法时,结果对象将为我们提供所有值。
Python3
from sqlalchemy import create_engine
user, password, host, database =\
'root', '123', 'localhost', 'geeksforgeeks'
engine = create_engine(
url=f'mysql+pymysql://{user}:{password}@{host}/{database}?charset=utf8')
connection = engine.connect()
# column name whose values we want
table_name = 'student'
column_name = 'name,dob'
# creating the sql query
query = f'SELECT {column_name} FROM {table_name}'
# running the query
result = connection.execute(query)
# fetching all the result and storing in
# values variable
values = result.fetchall()
# printing the output
print(values)
Python3
from sqlalchemy import create_engine
user, password, host, database =\
'root', '123', 'localhost', 'geeksforgeeks'
engine = create_engine(
url=f'mysql+pymysql://{user}:{password}@{host}/{database}?charset=utf8')
connection = engine.connect()
table_name = 'student'
# column names whose values we want
column_names = 'name,dob'
# creating the sql query
query = f'SELECT {column_names} FROM {table_name}'
# running the query
result = connection.execute(query)
# fetching all the result and storing in
# values variable
values = result.fetchall()
# printing the output
print(values)
输出:
示例 2:
在这里,如果用户想要获取多个列的值,那么您可以通过用逗号 (,) 分隔来指定查询中的列名。
Python3
from sqlalchemy import create_engine
user, password, host, database =\
'root', '123', 'localhost', 'geeksforgeeks'
engine = create_engine(
url=f'mysql+pymysql://{user}:{password}@{host}/{database}?charset=utf8')
connection = engine.connect()
table_name = 'student'
# column names whose values we want
column_names = 'name,dob'
# creating the sql query
query = f'SELECT {column_names} FROM {table_name}'
# running the query
result = connection.execute(query)
# fetching all the result and storing in
# values variable
values = result.fetchall()
# printing the output
print(values)
输出: