MST
星途 面试题库

面试题:Python使用MySQLdb库进行数据库查询操作

假设你有一个MySQL数据库,其中有一张名为`employees`的表,包含字段`id`(整数类型)、`name`(字符串类型)和`salary`(浮点类型)。请使用Python的MySQLdb库编写代码,查询出`salary`大于5000的所有员工的`name`字段,并将结果打印出来。
39.3万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import MySQLdb

# 连接数据库
db = MySQLdb.connect(host='localhost', user='yourusername', passwd='yourpassword', db='yourdatabase')
cursor = db.cursor()

# 执行SQL查询
sql = "SELECT name FROM employees WHERE salary > 5000"
cursor.execute(sql)

# 获取查询结果
results = cursor.fetchall()

# 打印结果
for row in results:
    print(row[0])

# 关闭数据库连接
cursor.close()
db.close()