查询数据
查询数据使用 SELECT 语句:
demo_mysql_test.py:
importmysql.connectormydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="runoob_db")mycursor = mydb.cursor()mycursor.execute("SELECT * FROM sites")myresult = mycursor.fetchall() # fetchall() 获取所有记录forxinmyresult: print(x)
执行代码,输出结果为:
(1,'RUNOOB','https://www.runoob.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')
也可以读取指定的字段数据:
demo_mysql_test.py:
importmysql.connectormydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="runoob_db")mycursor = mydb.cursor()mycursor.execute("SELECT name, url FROM sites")myresult = mycursor.fetchall()forxinmyresult: print(x)
执行代码,输出结果为:
('RUNOOB','https://www.runoob.com')
('Google','https://www.google.com')
('Github','https://www.github.com')
('Taobao','https://www.taobao.com')
('stackoverflow','https://www.stackoverflow.com/')
('Zhihu','https://www.zhihu.com')
如果我们只想读取一条数据,可以使用 fetchone() 方法:
demo_mysql_test.py:
importmysql.connectormydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="runoob_db")mycursor = mydb.cursor()mycursor.execute("SELECT * FROM sites")myresult = mycursor.fetchone()print(myresult)
执行代码,输出结果为:
(1,'RUNOOB','https://www.runoob.com')