How can I make company_id auto increment? - python

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

Related

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

AttributeError: 'tuple' object has no attribute 'encode' when inserting data using mysql-connector

The below program collects the users inputs and stores them, it then saves that data to a .csv / emails it to me and finally inserts that data into a MySQL database.
I am using mysql.connector for this, however I am getting the error:
AttributeError: 'tuple' object has no attribute 'encode'
when the program executes.
Here is the code, I think the problem is to do with the type of data trying to be inserted into the database, but I cannot be sure.
import mysql.connector
# ...
# Connect to MySQL Database and send user_input data to 'user' TABLE.
cnx = mysql.connector.connect(user='root', password='ash123', host='localhost', database='user_data_db')
cursor = cnx.cursor()
query = ("INSERT INTO user (user_id, first_name, last_name, age, postcode, email_address)"
"VALUES (%s, %s, %s, %s, %s, %s)", (user_id, firstname, lastname, age, postcode, email))
cursor.execute(query)
print("Executed Successfully")
cursor.close()
cnx.close()
Unless it's of the bytes or bytearray type, cursor.execute expects the first argument (SQL query) to have the encode method. query is a 2-tuple, tuples do not have that method and attempts to access it fail with AttributeError.
You can unpack query, in order to use its elements as positional arguments for cursor.execute:
cursor.execute(*query)
# = cursor.execute("INSERT INTO user (user_id, first_name, last_name, age, postcode, email_address)"
# "VALUES (%s, %s, %s, %s, %s, %s)", (user_id, firstname, lastname, age, postcode, email))

Finding the value of an auto-increment field

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

Categories

Resources