[英]INserting value in mysql DB using python
這是我的Mysql表架構
表:預訂欄:
id int(11) PK AI
apt_id varchar(200)
checkin_date date
checkout_date date
price decimal(10,0)
deposit decimal(10,0)
adults int(11)
source_id int(11)
confirmationCode varchar(100)
client_id int(11)
booking_date datetime
note mediumtext
Related Tables:property (apt_id → apt_id)
booking_source (source_id → id)
我正在嘗試使用python插入值。所以這是我所做的
sql = "INSERT INTO `nycaptBS`.`booking` (`apt_id`, `checkin_date`, `checkout_date`, `price`,`deposite` `adults`, `source_id`, `confirmationCode`, `client_id`, `booking_date`) VALUES ('%s','%s','%s','%s','%s','%d','%d','%s','%d','%s' )" % (self.apt_id,self.start_at,self.end_at,self.final_price,self.deposit,self.adults,self.source_id,self.notes,self.client_id,self.booking_date,self.notes)
x.execute(sql)
但是在執行上述腳本時,出現了錯誤。
sql = "INSERT INTO `nycaptBS`.`booking` (`apt_id`, `checkin_date`, `checkout_date`, `price`,`deposite` `adults`, `source_id`, `confirmationCode`, `client_id`, `booking_date`) VALUES ('%s','%s','%s','%s','%s','%d','%d','%s','%d','%s' )" % (self.apt_id,self.start_at,self.end_at,self.final_price,self.deposit,self.adults,self.source_id,self.notes,self.client_id,self.booking_date,self.notes)
TypeError: %d format: a number is required, not NoneType
我認為我的字符串格式化程序不正確,請幫幫我。
它看起來像booking_date,notes,source_id(也是您要插入注釋值2x?)為None
。 您可以在插入之前檢查/驗證每個值。
還請使用參數化查詢,而不是字符串格式
通常,您的SQL操作將需要使用Python變量中的值。 您不應該使用Python的字符串操作來匯編查詢,因為這樣做是不安全的。 它使您的程序容易受到SQL注入攻擊的影響(有關可能出現問題的幽默示例,請參見http://xkcd.com/327/ )。
而是使用DB-API的參數替換。 放? 作為要使用值的位置的占位符,然后提供值的元組作為游標的execute()方法的第二個參數。
就像是:
x.execute("INSERT INTO thing (test_one, test_two) VALUES (?, ?)", (python_var_one, python_var_two,))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.