Python基础 之 Python MySQL - mysql-connector 驱动 10
Python MySQL - mysql-connector 驱动
查询数据
查询数据使用 SELECT 语句:
demo_mysql_test.py:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="123456",
database="baidu_db"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM sites")
myresult = mycursor.fetchall() # fetchall() 获取所有记录
for x in myresult:
print(x)
执行代码,输出结果为:
(1, 'baidu', 'https://www.baidu.com')
(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')
(4, 'Taobao', 'https://www.taobao.com')
(5, 'stackoverflow', 'https://www.stackoverflow.com/')
(6, 'Zhihu', 'https://www.zhihu.com')
where 条件语句
如果我们要读取指定条件的数据,为了防止数据库查询发生 SQL 注入的攻击,我们可以使用 %s 占位符来转义查询的条件:
demo_mysql_test.py
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="123456",
database="baidu_db"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM sites WHERE name = %s"
na = ("baidu", )
mycursor.execute(sql, na)
myresult = mycursor.fetchall()
for x in myresult:
print(x)