update column a values to column b corresponding to particular id in python - mysql

I have written a code to read 2 columns(raw_id, notes) from mysql db using pymysql, which gives me list of dictionary. Now I want to extract id values, store it and update review column with notes column values for every raw_id at the record level. Can anybody help me with this.
db_data contains:
[OrderedDict([(u'raw_id', u'52c00'), (u'notes', u'awesome')]),
OrderedDict([(u'raw_id', u'54df0'), (u'notes', u'loved it')]),
OrderedDict([(u'raw_id', u'5cd00'), (u'notes', u'enjoyed')]),...]
Code I've used:
for row in db_data:
text = row.values()
r_id = text[0]
update_sql = "update raw_data set review = notes where
customer_id = {0} and raw_id = {1}"
res = sql_db.execute_write(update_sql, [inp_cust_id, r_id])
print res
Error I'm getting:
TypeError: not all arguments converted during string formatting

for row in db_data:
text = str(row.values())
r_id = str(text[0])
update_sql = "update raw_data set review = notes where
customer_id = {0} and raw_id = {1}"
res = sql_db.execute_write(update_sql, [inp_cust_id, r_id])
print res
try this

Related

Insert multiple values in MySQL with Python from an array

I am trying to insert data from my array into MySQL.
To my big surprise there were not many examples on how to do it if you perform a for-loop for your array, every example that I have found was from an already existing array list.
Thanks to Adrian below, we noticed that I need tuples for my list.
Updated code
connection = mysql.connector.connect(
host='localhost',
database='test',
user='root',
password='pass'
)
query = "INSERT INTO blue (created, published, publisher) VALUES (%s, %s, %s)"
array = []
# The idea here is to get all table rows in the page so you can group the values into rows that are going to be added to MySQL
tr = soup.find_all('tr')
for table_row in tr:
row_data = table_row.find_all('td')
insert_row = []
for data in row_data:
data = re.sub('<[^>]*>', '', str(data))
insert_row.append(data)
array.append(tuple(insert_row))
print(array)
cursor = connection.cursor()
cursor.executemany(query, array)
cursor.commit()
Getting close but at the moment I receive the following
IndexError: Tuple index out of range
mysql.connector.errors.ProgrammingError: Not enough parameters for the SQL statement
Thanks in advance!
I think you are mixing two ways of solving the problem...
One way is using the executemany method as described in the documentation
query = "INSERT INTO blues (created, published, publisher) VALUES (%s, %s, %s)"
array = []
# The idea here is to get all table rows in the page so you
# can group the values into rows that are going to be added to MySQL
tr = soup.find_all('tr')
for table_row in tr:
row_data = table_row.find_all('td')
insert_row = [None, None, None]
for idx in range(len(row_data)):
if row_data[idx] and idx < 3:
data = re.sub('<[^>]*>', '', str(row_data[idx]))
if data:
insert_row[idx] = data
array.append(tuple(insert_row))
cursor = connection.cursor()
cursor.executemany(query, array)
cursor.commit()
Another way is to build the query yourself...
query = "INSERT INTO blues (created, published, publisher) VALUES "
array = []
# The idea here is to get all table rows in the page so you can group the values into rows that are going to be added to MySQL
tr = soup.find_all('tr')
for table_row in tr:
row_data = table_row.find_all('td')
insert_row = []
for data in row_data:
data = re.sub('<[^>]*>', '', str(data))
insert_row.append(data)
array.append(tuple(insert_row))
values = []
for item in array:
row = [None, None, None]
for idx in range(len(item)):
row[idx] = item[idx]
values.append(str(tuple(row)))
query += ",".join(values)
cursor = connection.cursor()
cursor.execute(query)
cursor.commit()
Hope this helps...

Python errors occurring trying to insert data into a MySQL database table

I need to create an sql login/ sign up system for my program, however I keep hitting this error no matter what I do to change it. I need to have a randomly generated UTID, the users first and surname, along with a password that is verified, then the UserID is generated by taking the first three letters of the first name and the whole surname. I cant figure out how to overcome this.
I have tried to give the values inside the sql statement when inserting some literal datatypes, like writing "
c.execute('insert INTO tbl_Teachers (str(UTID), str(FName), str(SName), str(userPass), str(userID))VALUES(?,?,?,?,?);', var_insert) " but nothing seems to work.
def signup():
name = []
surname = []
print("Please enter the following details.")
user_type = str(input("Are you a teacher or a student: "))
if user_type == ("teacher") or ("Teacher"):
var_FName = str(input("First Name: "))
var_LName = str(input("Last Name: "))
var_password1 = str(input("Choose a password: "))
var_password2 = str(input("Please confirm password: "))
UTID = str(random.randint(0,100000))
print ("Your UserID is "+UTID+"")
name.append(var_FName)
surname.append(var_LName)
userID = []
for x in range (0, 3):
userID.append(var_FName[x])
for x in range (0,len(var_LName)):
userID.append(var_LName[x])
print (userID)
if var_password1 != var_password2:
print("Please try again.")
else:
var_insert = []
var_insert.append(UTID)
var_insert.append(var_FName)
var_insert.append(var_LName)
var_insert.append(str(var_password1))
var_insert.append(userID)
conn = sqlite3.connect('Program.db')
c = conn.cursor()
c.execute('insert INTO tbl_Teachers (UTID, FName, SName, userPass, userID)VALUES(?,?,?,?,?);', var_insert)
conn.commit()
InterfaceError: Error binding parameter 4 - probably unsupported type.
userID is supposed to be a string, but you're creating a list. Use string concatenation, not the append method.
userID = var_FName[0:3] + var_LName

Assign an only select value, to a only one variable

I'm stating with LUA and SQL statements. I have try, and I can display a SELECT or make an UPDATE, INSERT ... but i don't know how to assign an only returned select value, to a variable
mysql = require "luasql.mysql"
env = mysql.mysql()
conn = env:connect('table','user','pass','server')
--print(env,conn)
cursor,errorString = conn:execute([[select id from agent where extension = '9072']])
--print(cursor,errorString)
row = cursor:fetch ({}, "a")
while row do
print(string.format("%s", row.id))
row = cursor:fetch (row, "a")
end
-- close everything
cursor:close()
conn:close()
env:close()
I expect somehing like:
value=33
I'd do
sql = "select id from agent where extension = '9072' limit 1"
cursor,errorString = conn:execute(sql)
value = nil
if cursor then
row = cursor:fetch ({}, "a") -- we'll have 0 or 1 rows
if row then value = row.id end
end

jsonb_set code is executing but json_set code is not executing with postgresql table and error is

cursor = conn.cursor()
qry = """ UPDATE test_jsonb SET details = jsonb_set(details,'{address, flat}', '201'::jsonb) WHERE id = 1 """
cursor.execute(qry)
conn.commit()
print 'Json Element Updated Successfully'
Json Element Updated Successfully
cursor = conn.cursor()
qry = """ UPDATE test_json SET details = json_set(details,'{address, flat}', '201'::json) WHERE id = 1 """
cursor.execute(qry)
conn.commit()
print 'Json Element Updated Successfully'
ProgrammingError: function json_set(json, unknown, json) does not exist
LINE 1: UPDATE test_json SET details = json_set(details,'{address, ...
^
HINT: No function matches the given name and argument types. You might need to add explicit type cas

SQL Statement to update multiple columns with multiple where conditions

So I have the following SQL statement:
db.exec("UPDATE products SET product_description = '#{fj_description}' AND personalization = '#{fj_personalization}' AND product_photo = '#{fj_product_photo}' AND order_information = '#{fj_order_information}' WHERE campaign_name = '#{camp_name}' AND product_type = 'fleecejacket'")
All of the variables are returning the correct text that's retrieved from an HTML input field, so it seems to be something wrong with the sql statement. When I try to update the database, I get this error:
PG::InvalidTextRepresentation at /update_products
ERROR: invalid input syntax for type boolean: "soft, midweight fleece" LINE 1: UPDATE products SET product_description = 'soft, midweight f... ^
Try using comma instead AND:
"UPDATE products
SET product_description = '#{fj_description}',
personalization = '#{fj_personalization}',
product_photo = '#{fj_product_photo}',
order_information = '#{fj_order_information}'
WHERE campaign_name = '#{camp_name}'
AND product_type = 'fleecejacket'"