Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用SQLAlchemy对现有表执行简单的SELECT语句_Python_Mysql_Select_Sqlalchemy - Fatal编程技术网

Python 使用SQLAlchemy对现有表执行简单的SELECT语句

Python 使用SQLAlchemy对现有表执行简单的SELECT语句,python,mysql,select,sqlalchemy,Python,Mysql,Select,Sqlalchemy,互联网上没有一个地方有关于SQLAlchemy 1.0的简单SELECT语句的简单几行教程 假设我已经使用create_engine()建立了数据库连接,并且我的数据库表已经存在,我想知道如何执行以下查询: select name, age from users where name = 'joe' and age = 100 我认为下面将用于查询users数据库表 from sqlalchemy.sql import and_ s = sele

互联网上没有一个地方有关于SQLAlchemy 1.0的简单
SELECT
语句的简单几行教程

假设我已经使用
create_engine()
建立了数据库连接,并且我的数据库表已经存在,我想知道如何执行以下查询:

select
    name,
    age
from
    users
where
    name = 'joe'
    and
    age = 100

我认为下面将用于查询users数据库表

from sqlalchemy.sql import and_
s = select([users]).where(and_(users.c.name == 'joe', users.c.age == 100))
for row in conn.execute(s):
    print row

在试图找出同样的问题时发现了这一点

以下是我对答案的看法。我很想知道我是否错了/错在哪里,或者这一切是否都是熊猫的天性

要通过SQLAlchemy从表中选择数据,需要在SQLAlchemy中构建该表的表示。如果Jupyter Notebook的响应速度有任何指示,则在执行查询之前,不会填充该表示(使用现有数据库中的数据)

您需要
Table
来构建一个表。您需要
选择
从数据库中选择数据。您需要
元数据
。。。原因还不清楚,甚至在文档中()

然后可以迭代结果。有关如何返回一行或仅返回几行数据的信息,这对于较慢/较大的查询非常有用

for result in results:
    print(result)
我用一个本地数据库对此进行了检查,SQLAlchemy结果与原始SQL结果不相等。对于我的数据集来说,不同之处在于数字的格式。SQL返回float64(例如,
633.07
),而SQLAlchemy返回对象(我认为
Decimal
,例如
633.0700000000

这里有一些帮助:


编辑2021-02-14:更新上述代码以添加更多示例。尚未测试。

因为原始问题在select语句中有两列,它可能会让一些人对如何使用该语句进行写作感到困惑:

from sqlalchemy import and_  
stmt = select([users.columns.name,users.columns.age])  
stmt= stmt.where(and_(name=='joe',age==100)  
for res in connection.execute(stmt):  
    print(res)

您是如何声明引擎、数据库、连接、会话和导入语句的?接受这个答案吗?看来是对的,天哪!你救了我的命!官方文件中没有类似的东西!美好的我在上面的回答中加入了这一点。谢谢
from sqlalchemy import and_  
stmt = select([users.columns.name,users.columns.age])  
stmt= stmt.where(and_(name=='joe',age==100)  
for res in connection.execute(stmt):  
    print(res)