Reputation: 77
I have a table inside my data base as below that I'm trying to insert data into;
CREATE TABLE student (
student_id int AUTO_INCREMENT,
first_name varchar (20) NOT NULL,
last_name varchar (20) NOT NULL,
year_began int NOT NULL,
PRIMARY KEY (student_id)
Using python what needs to be added to the below code to get the auto incrementing primary key working for each new entry?
cursor = mydb.cursor()
cursor.execute ("INSERT INTO student (first_name, last_name, year_began) VALUES ('{}','{}','{}');".format(first_name, last_name, year_began))
mydb.commit()
cursor.close()
Apologies if this seems straight forward....newbie at this. Any help would be much appreciated.
Upvotes: 1
Views: 10405
Reputation: 71
https://www.w3schools.com/python/showpython.asp?filename=demo_mysql_primary_key
this might help.. You need to add the primary key attribute
Either on table creation or try executing after...
is the data already in the database and you want to add keys to existing data or data you will eventually add?
Upvotes: 2
Reputation: 1
I don't know python. But,you can try this.
print "ID of last record is ", int(cursor.lastrowid)
print "ID of inserted record is ", int(conn.insert_id())
the code must in front of mydb.commit()
Upvotes: 0