python使用mysql数据库
使用mysql数据库
关注公众号“轻松学编程”了解更多。
引入pymysql模块
方法一:
模块引入参考
中的安装第三方模块。
方法二:
使用命令
pip install pymysql
模块名称:pymysql。
步骤:
1、引入pymysql
2、配置并获得连接:pymysql.connect()
3、获得查询游标:cursor = conn.cursor()
4、执行SQL语句:affected = cursor.execute(sql)
5、从cursor中拿查询结果:cursor.fetchall()
6、提交结果:conn.commit()
7、断开连接:conn.close()
from django.test import TestCase
# Create your tests here.
import pymysql
if __name__ == '__main__':
#连接数据库
con = pymysql.connect(
host='localhost', #数据库所在地址URL
user='root', #用户名
password='123456', #密码
database='china', #数据库名称
port=3306, #端口号
charset='utf8'
)
#拿到查询游标
cursor = con.cursor()
#使用游标执行SQL语句
affected = cursor.execute('insert into t_provinces(proname) VALUES ("新省")')
print("插入成功,affected=",affected)
affected = cursor.execute('update t_provinces set proname="%s" where proname = "%s" ' % ('最新省','新省'))
print("修改成功,affected=", affected)
affected = cursor.execute('select * from t_provinces where proid =22 ')
print("查询成功,affected=", affected)
affected = cursor.execute('delete from t_provinces where proname="%s" ' % ('最新省'))
print("删除成功,affected=", affected)
#从游标中取出查询结果
ret = cursor.fetchall()
print(type(ret),ret)
# 如果是增删改需要提交
con.commit()
#断开连接
cursor.close()
con.close()
输出:
插入成功,affected= 1
修改成功,affected= 1
查询成功,affected= 1
删除成功,affected= 1
<class 'tuple'> ()
后记
【后记】为了让大家能够轻松学编程,我创建了一个公众号【轻松学编程】,里面有让你快速学会编程的文章,当然也有一些干货提高你的编程水平,也有一些编程项目适合做一些课程设计等课题。
也可加我微信【1257309054】,拉你进群,大家一起交流学习。
如果文章对您有帮助,请我喝杯咖啡吧!
公众号


关注我,我们一起成长~~

浙公网安备 33010602011771号