我有两个python文件:
1.create_account.py 2.run_sums.py
我想使用sum_balance函数从帐户表中获取列余额的总和。
但是,每次我运行run_sums.py时,总是出现错误:
“'int'对象不可调用”。我的编码有什么问题吗?
我对sqlalchemy很新鲜。
create_account.py:
import time
import random
from db_connect import get_conn
conn = get_conn().raw_connection()
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS account")
cursor.execute("""
CREATE TABLE account(
id INT NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
branch INT NOT NULL,
balance FLOAT NOT NULL)
""")
for i in xrange(0, 100000):
account = random.randint(1, 20)
balance = round(random.uniform(0, 100000), 2)
cursor.execute("""INSERT INTO account VALUES (DEFAULT, %d,%f)""" % (account, balance))
conn.commit()
run_sums.py:
import argparse
from sqlalchemy.orm import sessionmaker
import time
from db_connect import get_conn
from sqlalchemy import *
from create_account import account
parser = argparse.ArgumentParser()
parser.add_argument('S', type = int, help = 'number of sums')
parser.add_argument('I', help = 'isolation level')
args = parser.parse_args()
## Execute a sum query and return the results
def sum_balance(sess):
## 1. Execute a query that sum the balance of all accounts.
## 2. Fetch the result and return it.
acc = account()
sum_balance = sess.query(func.sum(acc.balance))
return sum_balance
## Create S sums operations
def S_sums(sess, S):
sums = []
start = time.time()
for i in xrange(0, S):
while True:
try:
sum = sum_balance(sess)
sums.append(sum)
except Exception as e:
print e
continue
break
stop = time.time()
return sums, stop-start
## Create the engine and run the sums
engine = get_conn()
Session = sessionmaker(bind=engine.execution_options(isolation_level=args.I, autocommit=True))
sess = Session()
sums, time = S_sums(sess, args.S)
print sums