ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

Django 执行sql python 执行sql

2022-08-07 17:01:44  阅读:463  来源: 互联网

标签:name python pymysql Django cursor sql print fetchone id


1 Django 操作mysql

参考地址: https://www.cnblogs.com/zhaoyingjie/p/9680842.html

from django.db import connection
cursor=connection.cursor()

自定义sql:

#插入操作 cursor.execute("insert into hello_author(name) values('郭敬明')") #更新操作 cursor.execute('update hello_author set name='abc' where name='bcd'') #删除操作 cursor.execute('delete from hello_author where name='abc'') #查询操作 cursor.execute('select * from hello_author')

 

 

2 python 操作mysql

1-1 安装pymysql

查看有没有装过pymysql模块

若,没有
在py文件中直接写 install pymysql,点击出现的红色小灯泡,然后选安装即可,如下图


1-2 获取数据库中表数据及控制光标移动


import pymysql


conn = pymysql.connect(
    host='127.0.0.1',  # ip
    port=3306,  # 端口
    user='root',  # mysql客户端登陆用户名
    passwd='1',  # mysql客户端登陆用密码
    charset='utf8',  # 千万不要加-
    # 指定要操作哪个库
    database='db3'
)  # 链接数据库
# 产生一个游标对象(类似在cmd中登陆mysql客户端后的哪个等待你输命令的闪烁的短下划线)
"""
将查询的结果以字典的形式返回
"""
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)



sql = 'select * from dep'
res = cursor.execute(sql)
# print(res)  # 5 表示:表dep中有5条数据




# ---用法1: 获取数据---


# print(cursor.fetchone())  # 只获取一条数据
# print(cursor.fetchmany(2)) # 获取指定条数据
# print(cursor.fetchall()) # 获取'光标后的'所有的数据 (使用较多)




# # 用法1.1
# print(cursor.fetchone())  # 只获取一条数据
# # {'id': 1, 'name': '教师部'}


# # 用法1.2
# # 拿到了所有的数据
# print(cursor.fetchall())
# # [{'id': 1, 'name': '教师部'}, {'id': 2, 'name': '后勤部'},
# # {'id': 3, 'name': '财务部'}, {'id': 4, 'name': '人事部'}, {'id': 5, 'name': '行政部'}]


# 用法1.3
# 获取指定条数据
# print(cursor.fetchmany(2))
# 结果: [{'id': 1, 'name': '教师部'}, {'id': 2, 'name': '后勤部'}]




# ---用法2: 控制光标移动---


# # 2.1 未控制前
# print(cursor.fetchone())
# print(cursor.fetchone())
# print(cursor.fetchall())
"""
{'id': 1, 'name': '教师部'}
{'id': 2, 'name': '后勤部'}
[{'id': 3, 'name': '财务部'}, {'id': 4, 'name': '人事部'}, {'id': 5, 'name': '行政部'}]
"""


# 2.1 控制后


# # 2.11
# print(cursor.fetchone())
# print(cursor.fetchone())
# cursor.scroll(2, 'relative')  # 光标相对于当前位置往后移几位
# print(cursor.fetchall())


"""
{'id': 1, 'name': '教师部'}
{'id': 2, 'name': '后勤部'}
[{'id': 5, 'name': '行政部'}]
"""


# 2.12
print(cursor.fetchone())
print(cursor.fetchone())
cursor.scroll(3, 'absolute')  # 光标相对于起始位置往后移几位
print(cursor.fetchall())


"""
{'id': 1, 'name': '教师部'}
{'id': 2, 'name': '后勤部'}
[{'id': 5, 'name': '行政部'}]
"""

 

标签:name,python,pymysql,Django,cursor,sql,print,fetchone,id
来源: https://www.cnblogs.com/tslam/p/16559371.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有