赞
踩
python项目连接MySQL数据库时,需要第三方库的支持。这篇文章使用的是PyMySQL库,适用于python3.x。
pip install PyMySQL
1.导入模块
import pymysql
2.连接数据库
db = pymysql.connect(host='localhost',
user='code_space',
password='code_space_pw',
database='demo_db')
3.创建游标对象
cursor = db.cursor()
# 或者
cursor = db.cursor(pymysql.cursors.DictCursor)
# cursor()不加参数的话,查询结果返回的是元组,pymysql.cursors.DictCursor返回的是字典
4)执行sql语句
# 查询
select_sql = " select id,name from user_info "
cursor.execute(select_sql)
# 使用 fetchone() 方法获取单条数据
data = cursor.fetchone()
# 使用 fetchall() 方法获取所有数据
data_list = cursor.fetchall()
# 增删改,这里只演示更新,其它类似
update_sql = " update user_info set name='头条号_code_space' where id = 1 "
cursor.execute(update_sql)
# 提交,执行更新
db.commit()
5)关闭数据库连接
cursor.close()
db.close()
import pymysql if __name__ == '__main__': db = pymysql.connect(host='localhost', user='root', password='root', database='others') # cursor()不加参数的话,查询结果返回的是元组,pymysql.cursors.DictCursor返回的是字典 cursor = db.cursor(pymysql.cursors.DictCursor) # 查询 select_sql = " select id,name from user_info " cursor.execute(select_sql) # 使用 fetchone() 方法获取单条数据 data = cursor.fetchone() print("fetchone()使用效果-->") print(data) # 使用 fetchall() 方法获取所有数据 cursor.execute(select_sql) data_list = cursor.fetchall() print("fetchall()使用效果-->") print(data_list) # 增删改,这里只演示更新,其它类似 update_sql = " update user_info set name='头条号_code_space' where id = 1 " cursor.execute(update_sql) # 提交,执行更新 db.commit() cursor.close() db.close()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。