用變量替換表名使用python和mysql連接器
顯示MysqL連接器的異常是告訴您該表在您的數(shù)據(jù)庫(kù)中不存在。
另外,您嘗試使用“ MachinePorn”作為參數(shù),但未在查詢中定義它,而是將其硬編碼為“ subredditName”。
我認(rèn)為您應(yīng)該在查詢中將數(shù)據(jù)庫(kù)定義為另一個(gè)參數(shù),它將正常運(yùn)行:
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')解決方法
我想動(dòng)態(tài)更改插入數(shù)據(jù)的表的變量名。
這目前有效,
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)''') data_value = (subreddit,_imageURL) c.execute(insert,data_value) cnx.commit() c.close() cnx.close()dataEntry('fake','fake','fake')
但是,當(dāng)我嘗試對(duì)表名(在這種情況下為“ FoodPorn”)執(zhí)行相同操作時(shí),對(duì)于動(dòng)態(tài)表(如本例中的MachinePorn),
def dataEntry(subreddit,_imageURL): cnx = mysql.connector.connect(**config) c = cnx.cursor() insert = ('''INSERT INTO subredditName (subreddit,%s)''') data_value = ('MachinePorn',subreddit,'fake')
我得到這個(gè)錯(cuò)誤,
mysql.connector.errors.ProgrammingError: 1146 (42S02): Table ’sytykr.subredditname’ doesn’t exist
這使我相信我無(wú)法通過(guò)這種方式執(zhí)行操作,因此我想問(wèn)一下如何執(zhí)行該操作,以便最終可以在表中傳遞變量名,而不必每次都對(duì)其進(jìn)行硬編碼。
相關(guān)文章:
