[英]A query to find the value of a variable (MySQL) and saving it to another variable for a different query
我有一個包含 2 列的表,它們將我的 internal_id 與 external_id 映射。
my_Id external_id
32312 23412
23234 12345
我從 API 獲取數據並收到 external_ids。 我正在嘗試使用 python 創建一個函數來檢查我從 api 獲得的 external_ids 是否存在於我的映射表中。 如果存在,對應的 my_id 應該是這個函數的輸出。 我想將它保存在一個變量中,該變量將與我從 API 獲得的其他信息一起插入到另一個表中。
def get_my_id(external_system_id):
query = cursor.execute("""SELECT my_id FROM table
WHERE external_system_id=:external_system_id, external_system_id=external_system_id""")
print(query)
return(query)
我的查詢是錯誤的,但不確定如何修改它以獲取變量並能夠使用收到的任何值編輯:我嘗試了 nbk 的解決方案,:
query = cursor.execute("""SELECT my_id FROM `tablename` WHERE customer_id=%s""",(customer_id,))
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s""", (external_system_id)' at line 2
您忘記替換占位符或切換到准備好的語句 Query 是一個數字,但它不是結果,因為如果該行存在,您必須獲取該行並將其返回數組元素。
對於 mysql.connector,代碼如下所示
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "password1",
database = "testdb"
)
mycursor = mydb.cursor(prepared=True)
my_id = 0
customer_id = 1
def get_my_id(customer_id):
result = mycursor.execute("SELECT my_id FROM `tablename` WHERE customer_id=%s",(customer_id,))
if result is None:
row = mycursor.fetchone()
return row[0]
else:
return 'Internal system_id not found'
my_id = get_my_id(customer_id)
print(my_id)
當我現在添加表 jaut 並添加列時,這將返回 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.