iT邦幫忙

0

python SQL 語法使用

  • 分享至 

  • xImage

您好:
請問

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()
 
sql = "SELECT * FROM sites WHERE name = %s"
na = ("RUNOOB", )
 
mycursor.execute(sql, na)
 
myresult = mycursor.fetchall()
 
for x in myresult:
  print(x)

請問
1.若 where 有like '%X%' ,這要如何使下語法 ,在SQL=" " 內
其他的in ,要如何用?

2.select 出來的結果
print(x[0]),可抓第一個欄位,是否有類似 x.欄位名 的方式
謝謝!

noway iT邦研究生 3 級 ‧ 2022-08-10 22:01:54 檢舉
LIKE 有想到
sql = "SELECT * FROM sites WHERE name = %s or name like %s or name in (%s)"
na = ("RUNOOB","%oo%","'Github','Taobao'")

但, in 沒反應
馬鈴薯 iT邦新手 5 級 ‧ 2022-08-14 23:48:02 檢舉
如果是MSSQL怎麼連接想順便詢問一下,希望可以\幫有想童問題的人一起問
HYHuang iT邦新手 5 級 ‧ 2022-08-18 11:08:30 檢舉
我是用 pymssql 套件~ 有成功唷
import pymssql
conn = pymssql.connect(server='xxx',
user='aa',
password='bbbbb',
database='asdqw')
cursor = conn.cursor()
query = "SELECT [TB001] AS 單別, [TB002] AS 單號, ........"
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
Felix
iT邦研究生 2 級 ‧ 2022-08-11 09:16:59

綁定資料

只能一對一綁定資料,不能用注入的方式。

如果用注入的方式,對應的資料就會是:

sql = 'SELECT * FROM table WHERE column IN (%s)'
cursor.execute('"A", "B", "C"')

# sql = SELECT * FROM table WHERE column IN ('"A", "B", "C"')

因此,正確的使用方式應該是:

sql = 'SELECT * FROM table WHERE column IN (%s, %s, %s)'
cursor.execute(sql, ('A', 'B', 'C'))

以字典型別輸出

import mysql.connector

cxn = mysql.connector.connect()
cursor = cxn.cursor(dictionary=True)
noway iT邦研究生 3 級 ‧ 2022-08-11 22:49:22 檢舉

謝謝
可是我一開始用【"】

sql = "SELECT * FROM table WHERE column IN (%s)"

cursor.execute("'A', 'B', 'C'")
這樣,預定會產生
SELECT * FROM table WHERE column IN ('A', 'B', 'C')
才對?

PYTHON 的「'」與「"」
不會跟js 一樣,有不同的效果?

有辦法 print出 執行的語法嗎?

謝謝

Felix iT邦研究生 2 級 ‧ 2022-08-15 08:51:51 檢舉

noway

如果要用注入的方式綁定,只能先對字串格式化來模擬注入:

sql = sql % ('A', 'B', 'C')
cursor.execute(sql)

# or

cursor.execute(sql % ('A', 'B', 'C'))

因為 execute 方法會跳脫特殊字元,防止 SQL 注入攻擊,所以注入的項目不會被視為 SQL 指令。

我要發表回答

立即登入回答