Skip to content Skip to sidebar Skip to footer

How To Divide 2 Varchar(255) Values And Insert Into Row (mysql, Python)

Table data: I have a table cpu with the columns name, price, id, mark, value Data format: The price value is $xxx.xx and the mark value is xxxxxx both stored as VARCHAR(255)'s. Que

Solution 1:

mycursor = mydb.cursor()

mycursor.execute("SELECT num, price, mark FROM cpu")

myresult = mycursor.fetchall()

for x in myresult:
  print(x)
  y = str(x)
  num, price, mark = y.split(',')
  num = num.replace("(", "")
  price = price.replace("'", "")
  price = price.replace(" ", "")
  price = price.replace("$", "")
  mark = mark.replace(")", "")
  mark = mark.replace("'", "")
  mark = mark.replace(" ", "")
  price = float(price)
  if mark != "None":
    mark = float(mark)
    value = mark/price
  else:
    value = 0
  value = round(value, 2)
  value = str(value)
  num = str(num)
  print(num)
  print(price)
  print(mark)
  print(value)
  sql = "UPDATE cpu SET value = " + value + " WHERE num = " + num +";"
  print(sql)
  mycursor.execute(sql)

  mydb.commit()

mydb.commit()

This is the code i made which solved my problem, I'm almost sure it could be improved so feel feel free to add another answer or comment and i'll change it.


Post a Comment for "How To Divide 2 Varchar(255) Values And Insert Into Row (mysql, Python)"