pyodbc 是否具有执行标量函数?
.net 中的 sql 库上的 executescalar 之类的东西?
pyodbc 游标有一个fetchone()方法。
cursor.execute("select user_name from users where user_id=?", userid)
row = cursor.fetchone()
if row:
print row.user_name
# or print row[0]
我不这么认为,但sqlalchemy确实如此(除了使用 ORM 等,它还可以用作 DB API 库的方便的高级接口)。举个例子:
import sqlalchemy
# using mssql as an example because sqlalchemy uses pyodbc as the default driver for MS Sql Server
engine = sqlalchemy.create_engine("mssql://myserver/mydb")
# first column of first row is returned
username = engine.scalar("select username from users where userid = 1")
您可以像这样简化pyodbc
调用:
name = cursor.execute("select user_name from users where user_id=?", userid).fetchval()
因为
获取值()
如果有结果,则返回第一行的第一列
和
*执行(sql,参数)
准备并执行一条 SQL 语句,返回 Cursor 对象本身