Python中的foo()函数如何与数据库交互
发布时间:2024-01-16 21:40:56
在Python中,与数据库进行交互通常需要使用第三方库,比如MySQLdb、PyMySQL、psycopg2等。以下是一个使用PyMySQL库与MySQL数据库进行交互的示例代码:
import pymysql
def foo():
# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='password', db='test_db', charset='utf8mb4')
try:
# 创建游标对象
cursor = conn.cursor()
# 查询数据
sql = "SELECT * FROM users"
cursor.execute(sql)
result = cursor.fetchall()
for row in result:
print(row)
# 插入数据
name = 'John'
age = 25
sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
cursor.execute(sql, (name, age))
conn.commit()
print("数据插入成功!")
# 更新数据
new_age = 30
sql = "UPDATE users SET age = %s WHERE name = %s"
cursor.execute(sql, (new_age, name))
conn.commit()
print("数据更新成功!")
# 删除数据
sql = "DELETE FROM users WHERE name = %s"
cursor.execute(sql, name)
conn.commit()
print("数据删除成功!")
except Exception as e:
print("数据库操作出现异常:", e)
finally:
# 关闭游标和数据库连接
cursor.close()
conn.close()
# 调用函数
foo()
以上代码中,首先通过pymysql.connect()函数连接到MySQL数据库。pymysql.connect()函数的参数包括数据库主机地址(host)、用户名(user)、密码(password)、数据库名称(db)等信息。
然后,通过conn.cursor()方法创建了游标对象。游标对象用于执行对数据库的操作,比如查询数据、插入数据、更新数据、删除数据等。
在进行数据操作之前,需要先编写相应的SQL语句,然后使用游标对象的execute()方法执行SQL语句。通过cursor.execute()方法执行SQL语句后,可以通过cursor.fetchall()方法获取查询结果。
在插入、更新、删除数据时,需要先执行conn.commit()方法提交事务,使得数据操作生效。
最后,在finally块中关闭游标和数据库连接,释放资源。
注意,以上示例代码中的数据库连接参数需要根据实际情况进行修改。
