Kyl*_*ndt 5 python mysql sql sqlite sqlalchemy
我正在解析日志并使用SQLAlchemy和Python将其插入MySQL或SQLite.现在我打开了与DB的连接,当我遍历每一行时,我在解析后插入它(这只是一个大表,现在对SQL不是很有经验).然后我在循环完成时关闭连接.汇总代码是:
log_table = schema.Table('log_table', metadata,
schema.Column('id', types.Integer, primary_key=True),
schema.Column('time', types.DateTime),
schema.Column('ip', types.String(length=15))
....
engine = create_engine(...)
metadata.bind = engine
connection = engine.connect()
....
for line in file_to_parse:
m = line_regex.match(line)
if m:
fields = m.groupdict()
pythonified = pythoninfy_log(fields) #Turn them into ints, datatimes, etc
if use_sql:
ins = log_table.insert(values=pythonified)
connection.execute(ins)
parsed += 1
Run Code Online (Sandbox Code Playgroud)
我的两个问题是: