简体   繁体   English

如何在sqlalchemy中更改现有数据库表的两个不同的列标题?

[英]How do I alter two different column headers of a pre-existing database table in sqlalchemy?

I am using sqlalchemy to reflect the columns of a table in a mysql database into a python script. 我正在使用sqlalchemy将mysql数据库中表的列反映为python脚本。 This is a database I have inherited and some of the column headers for the table have spaces in eg "Chromosome Position". 这是我继承的数据库,该表的某些列标题在“染色体位置”中带有空格。 A couple of the column headers also are strings which start with a digit eg "1st time". 几个列标题也是以数字开头的字符串,例如“第一次”。 I would like to alters these headers so that spaces are replaced with underscores and there are no digits at the beginning of the column header string eg "1st time" becomes "firsttime". 我想更改这些标题,以便用下划线替换空格,并且在列标题字符串的开头没有数字,例如“ 1st time”变为“ firsttime”。 I followed the advice given sqlalchemy - reflecting tables and columns with spaces which partially solved my problem. 我按照sqlalchemy的建议进行操作-用空格反映表和列 ,部分解决了我的问题。

from sqlalchemy import create_engine, Column, event, MetaData 
from sqlalchemy.ext.declarative import declarative_base, DeferredReflection
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.schema import Table
from twisted.python import reflect

Base = automap_base()
engine = create_engine('mysql://username:password@localhost/variants_database', echo=False)

#Using a reflection event to access the column attributes
@event.listens_for(Table, "column_reflect")
def reflect_col(inspector, table, column_info):
     column_info['key'] = column_info['name'].replace(' ', '_')

metadata = MetaData()
session = Session(engine)

class Variants(Base):
    __table__ = Table("variants", Base.metadata, autoload=True,      autoload_with=engine)

Base.prepare(engine, reflect=True)   
session = Session(engine)


a = session.query(Variants).filter(Variants.Gene == "AGL").first()
print a.Chromosome_Position

This allows me to return the values in a.Chromosome_Position. 这使我可以返回a.Chromosome_Position中的值。 Likewise if I change the method reflect_col to: 同样,如果我将方法reflect_col更改为:

@event.listens_for(Table, "column_reflect")
def reflect_col(inspector, table, column_info):
     column_info['key'] = column_info['name'].replace('1st time', 'firsttime')

a = session.query(Variants).filter(Variants.Gene == "AGL").first()
print a.firsttime

This also allow me to return the values in a.firsttime. 这也使我可以在a.firsttime中返回这些值。 However I am not able to alter both attributes of the column headers at the same time so changing the method to: 但是,我不能同时更改列标题的两个属性,因此将方法更改为:

@event.listens_for(Table, "column_reflect")
def reflect_col(inspector, table, column_info):
column_info['key'] = column_info['name'].replace(' ', '_')
column_info['key'] = column_info['name'].replace('1st time', 'secondcheck')

will only modify the last call to column_info which in this case is the column '1st time'. 只会修改对column_info的最后一次调用,在这种情况下,该调用为“第一时间”列。 So I can return the values of a.firsttime but not a.Chromosome_Position. 所以我可以返回a.firsttime的值,但不能返回a.Chromosome_Position。 How do I change both column name features in the same reflection event? 如何在同一反射事件中更改两个列名称功能?

It seems that you are overwriting the first value after the second replacement. 似乎您在第二次替换后覆盖了第一个值。 I hope chaining the .replace works: 我希望链接.replace工程:

@event.listens_for(Table, "column_reflect")
def reflect_col(inspector, table, column_info):
   column_info['key'] = column_info['name'].replace(' ', '_').replace('1st_time', 'secondcheck')

[EDIT]: You have to also make sure that the changes wouldn't clash. [编辑]:您还必须确保所做的更改不会冲突。

Because in this example the first change replaces spaces with underscore, you have to adapt the second replacement, as it's already called 1st_time when the second replace is called. 因为在此示例中,第一个更改用下划线替换空格,所以您必须适应第二个替换,因为在调用第二个替换时它已被称为1st_time

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 SQlAlchemy ORM 会话查询预先存在的表? - How to query pre-existing table from SQlAlchemy ORM session? 如何将预先存在的 python 项目导入 Eclipse? - How do I import a pre-existing python project into Eclipse? 如何加载预先存在的数据烧瓶-sqlalchemy - how to load pre-existing data flask-sqlalchemy 使用Flask,python和postgresql如何连接到预先存在的数据库? - using Flask, python and postgresql how can I connect to a pre-existing database? SQLAlchemy的; 将主键设置为预先存在的db表(不使用sqlite) - Sqlalchemy; setting a primary key to a pre-existing db table (not using sqlite) Python方法或预先存在的模块通过标头(而不是列ID)访问csv - Python method or pre-existing module to access csv via headers instead of column ID's 使用数据库中预先存在的数据编辑SelectMultipleField - editing a SelectMultipleField with pre-existing data in the database 如何使用 SQLAlchemy 将默认/预先存在的行作为准备使用的对象? - How to have default/pre-existing rows as ready to use objects using SQLAlchemy? Pandas:使用从预先存在的列计算的值在数据框中创建两个新列 - Pandas: create two new columns in a dataframe with values calculated from a pre-existing column 如何重新输入预先存在的 django 应用程序 - How to reenter a pre-existing django app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM