使用Python向MySQL表添加單一鍵值對
P粉111227898
P粉111227898 2023-09-04 21:36:42
0
1
553
<p>我正在嘗試從 python 向 mysql 表添加一個值。我已經嘗試了大約五種不同的方法,但仍然收到錯誤訊息,指出當我呼叫插入時,表中的其他鍵沒有傳遞值。問題是我不想插入任何其他值,只想插入一個特定的按鍵。這是我目前擁有的程式碼,提前感謝您的幫助</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):欄位「userid」沒有 預設值</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粉111227898
P粉111227898

全部回覆(1)
P粉742550377

正確的方法是不使用 python,而只使用 MySQL 查詢

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板