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.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top