Python基础 之 Python MySQL - mysql-connector 驱动 8
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 条件语句
如果我们要读取指定条件的数据,可以使用 where 语句:
demo_mysql_test.py
读取 name 字段为 baidu 的记录:
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 ='baidu'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
执行代码,输出结果为:
(1, 'baidu', 'https://www.baidu.com')