簡體   English   中英

用變量替換表名。 使用python和mysql連接器

[英]Replace table name with variable. Using python and mysql connector

我想動態更改插入數據的表的變量名。

這目前有效,

def dataEntry(subreddit, _title, _post_url, _imageURL):
    cnx = mysql.connector.connect(**config)

    c = cnx.cursor()
    insert = ("""INSERT INTO FoodPorn
                    (subreddit, title, post_url, imageURL)
                    VALUES (%s, %s, %s, %s)""")

    data_value = (subreddit, _title, _post_url, _imageURL)

    c.execute(insert, data_value)
    cnx.commit()
    c.close()
    cnx.close()

dataEntry("fake", "fake", "fake", "fake")

但是當我嘗試對表名(在這種情況下為“ FoodPorn”)執行相同操作時,對於動態表(如本例中的MachinePorn),

def dataEntry(subreddit, _title, _post_url, _imageURL):
    cnx = mysql.connector.connect(**config)

    c = cnx.cursor()
    insert = ("""INSERT INTO subredditName
                    (subreddit, title, post_url, imageURL)
                    VALUES (%s, %s, %s, %s, %s)""")

    data_value = ("MachinePorn", subreddit, _title, _post_url, _imageURL)

    c.execute(insert, data_value)
    cnx.commit()
    c.close()
    cnx.close()

dataEntry("fake", "fake", "fake", "fake")

我得到這個錯誤,

mysql.connector.errors.ProgrammingError: 1146 (42S02): Table 'sytykr.subredditname' doesn't exist

這使我相信我無法通過這種方式執行操作,因此我想問一下如何執行該操作,以便最終可以在表中傳遞變量名,而不必每次都對其進行硬編碼。

顯示mysql連接器的異常是告訴您該表在您的數據庫中不存在。

另外,您嘗試使用“ MachinePorn”作為參數,但未在查詢中定義它,而是將其硬編碼為“ subredditName”。

我認為您應該在查詢中將數據庫定義為另一個參數,它將正常運行:

def dataEntry(subreddit, _title, _post_url, _imageURL):
     cnx = mysql.connector.connect(**config)

     c = cnx.cursor()
     insert = cnx.escape_string("INSERT INTO MachinePorn (subreddit, title, post_url, imageURL) VALUES (%s, %s, %s, %s)")

     data_value = (subreddit, _title, _post_url, _imageURL)

     c.execute(insert, data_value)
     cnx.commit()
     c.close()
     cnx.close()

dataEntry("fake", "fake", "fake", "fake")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM