Python基础 之 Python MySQL - mysql-connector 驱动 9
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 条件语句
如果我们要读取指定条件的数据,可以使用通配符 %:
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 url LIKE '%oo%'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
执行代码,输出结果为:
(1, 'baidu', 'https://www.baidu.com')
(2, 'Google', 'https://www.google.com')