Postgresql insert data error when using python - 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))

Related

importing values of a python dictionary as data to an existing mysql table

I have problem with storing values of a python dictionary as data to an existing mysql table
I tried to use the code below but it's not working.
db = mysql.connect(
host="localhost",
user="root",
passwd="123456",
database="tgdb"
)
cursor = db.cursor()
val = ', '.join("'" + str(x) + "'" for x in dict.values())
sql = "INSERT INTO tgdb.channel(user_name, image_url, name,
number_of_members, description, channel_url) VALUES (%s, %s, %s, %s, %s,
%s)"
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "record inserted.")
"you have an error in your SQL syntax"
As writed #Torxed shouldn't translate dict in string, you can write just that:
cursor.execute(sql, list(dict.values())

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

How to store data into database using PyMYSQL in python

I am scraping a website and getting the companies details from it, Now I trying to store the data into database. But I am getting some error like
raise InternalError(errno, errorvalue)
pymysql.err.InternalError: (1054, "Unknown column 'companyaddress' in 'field list'")
Here is my code
for d in companydetail:
lis = d.find_all('li')
companyname = lis[0].get_text().strip()
companyaddress = lis[1].get_text().strip()
companycity = lis[2].get_text().strip()
try:
companypostalcode = lis[3].get_text().strip()
companypostalcode = companypostalcode.replace(",","")
except:
companypostalcode = lis[3].get_text().strip()
try:
companywebsite = lis[4].get_text().strip()
except IndexError:
companywebsite = 'null'
print (companyname)
print (companyaddress)
print (companycity)
print (companypostalcode)
print (companywebsite)
try:
with connection.cursor() as cursor:
print ('saving to db')
cursor.execute("INSERT INTO company(companyname,address,city,pincode,website) VALUES (companyname,companyaddress,companycity,companypostalcode,companywebsite)")
connection.commit()
connection.close()
I am getting my data which I want but it I am not able to store data into database.
The result which I get while print (companyname) and print (campanyaddress) is :
NINGBO BOIGLE DIGITAL TECHNOLOGY CO.,LTD.
TIANYUAN INDUSTRIAL ZONE CIXI NINGBO
ZHEJIANGNINGBO
315325
http://www.boigle.com.cn
You cannot simply use variable names inside a query string as you do:
cursor.execute("INSERT INTO company(companyname,address,city,pincode,website) VALUES (companyname,companyaddress,companycity,companypostalcode,companywebsite)")
Instead, pass your variables into the query making it parameterized:
params = (companyname, companyaddress, companycity, companypostalcode, companywebsite)
cursor.execute("""
INSERT INTO
company
(companyname, address, city, pincode, website)
VALUES
(%s, %s, %s, %s, %s)
""", params)
In
cursor.execute("INSERT INTO company(companyname,address,city,pincode,website) VALUES (companyname,companyaddress,companycity,companypostalcode,companywebsite)")
the values in the second bracket are interpreted as table fields, rather than as python variables. Try
cursor.execute("""INSERT INTO company(
companyname,address,city,pincode,website)
VALUES (%s, %s, %s, %s, %s)""",
(companyname, companyaddress, companycity,
companypostalcode, companywebsite))
instead. You may also want to consult the docs on that.

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