婚介网站建站,wordpress自定义登录框插件,装潢设计软件有哪些,郑州网络安全科技馆一、应用场景
python项目连接MySQL数据库时#xff0c;需要第三方库的支持。这篇文章使用的是PyMySQL库#xff0c;适用于python3.x。
二、安装
pip install PyMySQL三、使用方法
导入模块
import pymysql连接数据库
db pymysql.connect(hostlocalhost,usercode_space…一、应用场景
python项目连接MySQL数据库时需要第三方库的支持。这篇文章使用的是PyMySQL库适用于python3.x。
二、安装
pip install PyMySQL三、使用方法
导入模块
import pymysql连接数据库
db pymysql.connect(hostlocalhost,usercode_space,passwordcode_space_pw,databasedemo_db)创建游标对象
cursor db.cursor()
# 或者
cursor db.cursor(pymysql.cursors.DictCursor)# cursor()不加参数的话查询结果返回的是元组pymysql.cursors.DictCursor返回的是字典执行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()关闭数据库连接
cursor.close()
db.close()四、测试demo
# -*- coding: utf-8 -*-
import pymysqlif __name__ __main__:db pymysql.connect(hostlocalhost,userroot,passwordroot,databaseothers)# 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()