python怎么添加列,每次我运行python程序时如何添加新列

i want my table to have 1st column as roll no,second as name.whenever i run python program i want to add a column of date in table.and in that new column i want to populate the list which i get from user.list will contain values 'P','A','P','P' etc.how to go about it?

i tried first adding a column by alter command and then inserting data but nothing works.

choice1=raw_input("\nEnter 'y' or 'n' to add new column:\n")

if choice1 is 'y':

cursor.execute(" ALTER TABLE table1 ADD datecolumn varchar(20)")

db.commit()

for i in xrange(0,10):

if students[i] is 'A':

cursor.execute("insert into table1(datetime) values ('A')")

db.commit()

elif students[i] is 'P':

cursor.execute("insert into table1(datetime) values ('P')")

db.commit()

解决方案

Don't change your DB design at runtime, but design it in a way that you will change the data not the structure.

You could have two tables. One called Student with columns rollno and name, maybe PK on rollno if it is unique.

Then have another table called Thing (any suitable name, but I don't know what your data is about) with three columns when (datetime), value (any suitable name) (CHAR(1)) and student (same type as rollno).

Define PK over both when and value to ensure that each student has only one value per date. Define a FK from Thing.student to Student.rollno. Now your DB takes care of keeping your data (mostly) consistent.

Define indices depending on your needs of selects, inserts and updates over the different columns.

Then for querying join both tables to get the desired result, e.g.

select s.name, t.value

from Student s

left join Thing t on t.student = s.rollno

where t.when == 'whenever'

(I am not sure about the mysql dialect, so maybe some more quotes are needed. Please feel free to edit.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值