Finding the value of an auto-increment field - python

I have a simple registration form which creates a new record in "Students" table:
cur = con.cursor()
query = "INSERT INTO students (Name, Address, Major, Phone, Email, Password) values (%s, %s, %s, %s, %s, %s)"
args = [name, address, major,phone, email, password]
cur.execute(query, args)
con.commit()
The column Id is auto-incremented, so in order to get the last Id, I select Max
query = "SELECT MAX(Id) FROM students;"
cur.execute(query)
id = cur.fetchone()[0]
It works in my little homework-project, but how would it be done in a heavy-loaded project, where there is a possibility of something being created before the select statement?

Use lastrowid attribute:
...
cur.execute(query, args)
id = cur.lastrowid

Related

How can I make company_id auto increment?

company_id entry box inserts data to my mysql database but it is not auto incremented, how can I turn it into auto increment?
query = "INSERT INTO basic_data(company_id, lastname, firstname, middlename) VALUES(%s, %s, %s, %s)"
cursor.execute(query, (t1.get(), t2.get(), t3.get(), t4.get()))

How to solve that execute() takes no keyword arguments

I want to insert data to database table with these python 3 script,
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
for val in values:
cursor.execute(sql, params=val)
db.commit()
print("{} data ditambahkan".format(cursor.rowcount))
but I got error type "TypeError: execute() takes no keyword arguments". could someone help solve this error?
You can directly pass the query and values with it in the form of list.
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
for val in values:
cursor.execute(sql, list(val))
db.commit()
print("{} data ditambahkan".format(cursor.rowcount))
Or you can use executemany to insert all the values at one time.
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
cursor.executemany(sql, values)
db.commit()
print("{} data ditambahkan".for

Nested Query: SELECT within INSERT Query

I have two tables say Doctors and patients. I need to fetch the doctors id (unique) from the doctors table and then pass it to a column of the patient's table during the INSERT operation. How can I write the query for that.
I tried the below way but it gives programming error:
usr = self.current_user
self.db.execute("INSERT INTO patients ("SELECT id FROM doctors WHERE doctors.id = '%s' " % usr )(mrd, name, age, gender, address, phone_number, blood_group,\
registration_date, did) values ('%s', '%s', '%s', '%s','%s','%s','%s','%s', '%s')" % (mrd,name,age,gender,\
address,phoneNumber, bloodGroup,dateOfReg,usr),callback=self.add_response)
I am trying to execute this in python tornado framework with psql backend
SELECT should be in VALUES section
The query will be like so
doctor_id = self.db.execute("SELECT id FROM doctors WHERE doctors.id = '%s' " % usr ).fetchone()
self.db.execute("INSERT INTO patients(mrd, name, age, gender, address, phone_number, blood_group,registration_date, did, doctor_id) values (%s, %s, %s, %s,%s,%s,%s,%s,%s, %s)" % (mrd,name,age,gender,address,phoneNumber, bloodGroup,dateOfReg,usr, doctor_id),callback=self.add_response)

mysql.connector in python / cursor in for-loop only working for first row of table

I have a table and I want to translate columns 'topic' and 'review' of a row and store the entire table with their translations into a new table. It seems that the for-loop doesn't iterate over all rows of the input table. Only the first row is stored into the new table. Why?
database = mysql.connector.connect(user='root', password='root', host='localhost', database='test')
DBcursor = database.cursor(buffered=True)
query = ("SELECT * FROM test_de")
DBcursor.execute(query)
for (id, user_name, date, country, version, score, topic, review, url) in DBcursor:
topic_trans = translate(topic, 'en')
review_trans = translate(review, 'en')
add_translation = ("INSERT INTO test_de_en(id, user_name, date, country, version, score, topic, review, url)"
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)")
translation_data = (id, user_name, date, country, version, score, topic_trans, review_trans, url)
DBcursor.execute(add_translation, translation_data)
database.commit()
DBcursor.close()
database.close()

Postgresql insert data error when using python

I am trying to insert data to the table that was created earlier using python script. Here is the code I am trying to execute. I want to insert data into table with date as well.
date_today = dt.date.today()
conn = psycopg2.connect(host = serverip, port = port, database = database, user = uid, password = pwd)
cursor = conn.cursor()
cursor.execute("INSERT INTO My_TABLE (Date, Class, Total_students, failed_students, Percent_passed_students) VALUES (date_today, 'Class Name', int1, int2, int3)")
print "Data Inserted successfully"
conn.commit()
conn.close()
Here is the error I see from my job. what am i missing here?
psycopg2.ProgrammingError: column "date_today" does not exist
I created the table using different job with the following query:
cursor.execute("""CREATE TABLE MY_TABL(Date date, Lob varchar(30), Total_Students int, failed_students int, Percent_passed_students int)""")
And the table is created with above five columns.
This line:
cursor.execute("INSERT INTO My_TABLE (Date, Class, Total_students, failed_students, Percent_passed_students) VALUES (date_today, 'Class Name', int1, int2, int3)")
Is the incorrect way to dynamically insert values into a database.
Here's a functional and correct example:
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
And applying it in your case...
cursor.execute("INSERT INTO My_TABLE VALUES (%s, %s, %s, %s, %s)", (date_today, 'Class Name', int1, int2, int3))

Categories

Resources