1. 程式人生 > >python一行sql太長折成多行並且有多個引數

python一行sql太長折成多行並且有多個引數

sql語句

有一個非常長的sql,用編輯器開啟編寫的時候太長了導致編寫非常吃力,而且容易錯亂,我想做的是把A,B,C三個變數賦值到sql中的欄位中去

A=1
B=2
C=3

sql = "update student t set t.name = '',t.sex = '',t.age = '',t.height = '',t.weight = '',t.class = '',t.stuid = '',t.xxx = '' where t.stuid= '' and t.xxx = '';"

摺疊多行後寫法

解決方案如下:

可以通過()小括號將每一行的字串整齊拼接,回車以後會自動將每行的字串進行拼接,並且將每個需要傳參的欄位加上 %s,在括號結束之前在用%(變數名字,變數名字,變數名字)依次進行賦值。最終完美解決。

A=1
B=2
C=3
sql = ("update student t set t.name = '%s',"
                    "t.sex = '%s',"
                    "t.age = '%s',"
                    "t.height = '%s',"
                    "t.weight = '%s',"
                    "t.class = '%s',"
                    "t.stuid = '%s',"
                    "
t.xxx = '%s'" " where t.stuid= '%s'" " and t.xxx = 'P';
" %(A,B,A,B,B,A,A,B,C) )