如何使用sqlAlchemy调用MySQL的存储过程?
我尝试了以下代码:
import webapp2
from sqlalchemy import *
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import create_session
from sqlalchemy import create_engine
class TestSQL(webapp2.RequestHandler):
def get(self):
Base = automap_base()
engine = create_engine(('mysql://root@127.0.0.1:3306/testDB?unix_socket=/cloudsql/School=:mysqlserver'))
# reflect the tables
Base.prepare(engine, reflect=True)
metadata = MetaData(bind=engine)
users = Table('Student', metadata, autoload=True)
student = metadata.tables ["Student"]
session = create_session()
pro = session.execute("p_get_teacher_requests", (1,0))
self.response.write(pro)
这是我得到的错误:
UnboundExecutionError: Could not locate a bind configured on SQL expression or this Session
答案 0 :(得分:6)
经过一些研究,以及许多方法,它使用以下代码:
import webapp2
from sqlalchemy import *
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import create_session
from sqlalchemy import create_engine
class TestSQL(webapp2.RequestHandler):
def get(self):
self.response.headers["Content-Type"] = "application/json"
Base = automap_base()
engine = create_engine(('mysql://root@IP:3306/School?unix_socket=/cloudsql/school:mysqlserver'))
# reflect the tables
Base.prepare(engine, reflect=True)
metadata = MetaData(bind=engine)
users = Table('Student', metadata, autoload=True)
student = metadata.tables ["Student"]
session = create_session()
connection = engine.raw_connection()
cursor = connection.cursor()
cursor.callproc("p_get_teacher_requests", [1,0])
results = list(cursor.fetchall())
cursor.close()
connection.commit()
self.response.write(results)