What is the MySql Update equivalent of this? - python

What is the MySql UPDATE equivalent of this ?
INSERT INTO items (title, url) VALUES (%s, %s)", (listtitle[0], listlink[0]))

"update items
set title = '{0}',
url = '{1}'
where COLUMN = VALUE
and COLUMN2 = VALUE2".format(listtitle[0], listlink[0])
Replace the words in uppercase with the specific values or otherwise you would update the whole table.
Unknown column in 'field list' error on MySQL Update query
Try this
self.cursor.execute("UPDATE items SET descs ='{0}'".format(item['title'][0]))
instead of this
self.cursor.execute('UPDATE items SET descs =%s' % item['title'][0])

Try this:
"UPDATE items SET title = %s, url= %s" % listtitle[0], listlink[0]

Related

Inserting a list into MySQL table, id wise

I am trying to insert a list into 1 single column in a row .How do I make the list go in a column in the same row with the same ID? I cannot get the syntax right.
social_media is a list like this
['https://twitter.com/eddylazzarin?ref=cypherhunter', 'https://www.linkedin.com/in/eddy-lazzarin-66059749?ref=cypherhunter', 'https://a16z.com/author/eddy-lazzarin/?ref=cypherhunter']
This is my code
sql = cursor.execute(f"SELECT inv_id FROM Investors WHERE name =\'{name}\'")
pid = cursor.fetchone()
pidf = str(pid)[1:2]
pidff = int(pidf)
try:
cursor.execute("INSERT INTO team_members(inv_id,mem_name,picture,experience) VALUES(%s, %s, %s, %s)", (pidff, port_name, headshot, work_ex,))
list_str = '|'.join(str(item) for item in so_links)
cursor.execute(f"UPDATE team_members WHERE mem_name=\'{port_name}\' SET social_media ('{list_str}')")
raise e
inv_id is the FOREIGN_KEY.
However I cannot get the right syntax
Error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'WHERE mem_name='Eddy Lazzarin' SET social_media
('https://twitter.com/eddylazzar' at line 1
You have missing = in SET & wrong position of it
cursor.execute("UPDATE team_members SET social_media = %s WHERE mem_name=%s",(list_str,port_name))
see the docs

mysql.connector.errors.ProgrammingError: Failed processing format-parameters; Python 'list' cannot be converted to a MySQL type

question answered
I am attempting to insert a value into my table where it selects an ID by matching it with its name and inserting it into a second table. However when I print out the selected value it prints [(1,)] which is classed as a list. So when it tries to insert the value into a table I receive the error that im trying to insert a list when I just want the value 1.
the code for it is in python and its shown below:
def createaudit():
sitename2_info = sitename.get()
print(sitename2_info, "testing2")
name2_info = name2.get()
print(name2_info)
name3_info = name3.get()
print(name3_info)
# Sql code for writing the data that was written in the regsitering page.
cursor = cnn.cursor()
# the site query matches the inputted username with the corresponding userID and inserts the userID into userID_fk
siteIDQuery = "SELECT siteID FROM Sites WHERE siteName = %s"
cursor.execute(siteIDQuery, [sitename2_info])
siteID_fetch = cursor.fetchall()
print(siteID_fetch)
sitequery = "INSERT INTO `audit`(`siteID_fk`, `auditor1`, `auditor2`) VALUES (%s, %s, %s)"
sitequery_vals = (siteID_fetch, name2_info, name3_info)
cursor.execute(sitequery, sitequery_vals)
# prints how many rows were inserted to make sure values are put into the database
print(cursor.rowcount)
cnn.commit()
cursor.close()
cnn.close()

Insert Data Into A Table Using The Same Foreign Key Value

I'm using SQL Server, Python, pypyodbc.
The tables I have are:
tbl_User: id, owner
tbl_UserPhone: id, number, user_id
user_id is the primary key of User and the foreign key of UserPhone.
I'm trying to insert 2 different phones to the same user_id using pypyodbc.
This is one of the things I tried that did not work:
cursor = connection.cursor()
SQLCommand = ("INSERT INTO tbl_UserPhones"
"(id,number,user_id)"
" VALUES (?,?,?)")
values = [userphone_index, user_phone,"((SELECT id from tbl_User where id = %d))" % user_id_index]
cursor.execute(SQLCommand, values)
cursor.commit()
Based on your comments, you have an identity column in tbl_UserPhones. Based on the column names I'm guessing it's the ID column.
The exception you get is very clear - you can't insert data into an identity column without specifically setting identity_insert to on before your insert statement. Basically, messing around with identity columns is bad practice. it's better to let Sql server to use it's built in capabilities and handle the insert to the identity column automatically.
You need to change your insert statement to not include the id column:
Instead of
SQLCommand = ("INSERT INTO tbl_UserPhones"
"(id,number,user_id)"
" VALUES (?,?,?)")
values = [userphone_index, user_phone,"((SELECT id from tbl_User where id = %d))" % user_id_index]
try this:
SQLCommand = ("INSERT INTO tbl_UserPhones"
"(number,user_id)"
" VALUES (?,?)")
values = [user_phone,"((SELECT id from tbl_User where id = %d))" % user_id_index]
SQLCommand = ("INSERT INTO tbl_UserPhones"
"(id,number,user_id)"
" VALUES (?,?,?)")
user_sqlCommand = cursor.execute("(SELECT id FROM tbl_User WHERE id = %d)" % user_index).fetchone()[0]
values = [userphone_index, user_phone, user_sqlCommand]
This was the solution.

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.

How do I avoid inserting duplicate data in PostgreSQL?

How to avoid inserting duplicate data? I only want to insert data that does not already exist. I have written following queries but its not working properly. I'm using PostgreSQL.
title_exits = cursor.execute ("SELECT title,pageid FROM movie_movie WHERE title = %s AND pageid = %s;",(title,pageid))
if title_exits == 0:
cursor.execute("INSERT INTO movie_movie (title,pageid,slug,language) values (%s,%s,%s,%s);",(title,pageid,slug,id))
db.commit()
Update: I tried result = cursor.fetchone ("SELECT count(*) FROM movie_movie WHERE title = %s AND pageid = %s;",(title,pageid)). But I'm getting error message. TypeError: fetchone() takes not arugments (2 given).
Answer related to your update:
You should use "%" symbol instead comma:
result = cursor.fetchone ("SELECT count(*) FROM movie_movie WHERE title = %s AND pageid = %s;" % (title,pageid))
update
as #no_freedom said in comments, think better approach would be
result = cursor.fetchone ("SELECT count(*) FROM movie_movie WHERE title = :1 AND pageid = :2", [title,pageid])
But i'm not sure, just try it.
Try to define title field as unique(must define as varchar(constant_length)). Then try insert title into database if title exists, db return error else will insert
As I suspected (and #tony points out) cursor.execute does not return the number of rows. It always return None.

Categories

Resources