Home  >  Q&A  >  body text

Add a single key-value pair to a MySQL table using Python

<p>I'm trying to add a value to a mysql table from python. I've tried about five different methods and I still get an error stating that no other key in the table has a value passed when I call insert. The problem is that I don't want to insert any other value, only a specific key. This is the code I have so far, thanks in advance for any help</p> <pre class="brush:php;toolbar:false;">cursor.execute("SELECT * FROM SONG") result = cursor.fetchall() sname = str(input("What is the name of the song you are looking for: ")) for row in result: title = row[0] if(title == sname): sql = ("INSERT INTO USER (s_id) VALUES (%s)") val = row[1] cursor.execute(sql, (val,))</pre> <p>mysql.connector.errors.DatabaseError: 1364 (HY000): Field 'userid' does not exist Default value</p> <pre class="brush:php;toolbar:false;">CREATE TABLE USER (username VARCHAR(20), userid CHAR(3), a_id CHAR(3), s_id CHAR(3), PRIMARY KEY (userid), FOREIGN KEY (a_id) REFERENCES ALBUM(a_id), FOREIGN KEY (s_id) REFERENCES SONG(s_id)); CREATE TABLE PLAYLIST (p_name VARCHAR(20), p_id CHAR(3) NOT NULL, userid CHAR(3), s_id CHAR(3), PRIMARY KEY (p_id), FOREIGN KEY (userid) REFERENCES USER(userid), FOREIGN KEY (s_id) REFERENCES SONG(s_id));</pre></p>
P粉111227898P粉111227898433 days ago544

reply all(1)I'll reply

  • P粉742550377

    P粉7425503772023-09-05 18:35:11

    The correct way is not to use python, but only use MySQL query

    sname = str(input("What is the name of the song you are looking for: "))
        sql = ("INSERT INTO USER (s_id) select id from SONG where name= '%s'")
        cursor.execute(sql)

    https://www.w3schools.com/sql/sql_insert_into_select.asp

    reply
    0
  • Cancelreply