Python教程

Django 执行sql python 执行sql

本文主要是介绍Django 执行sql python 执行sql,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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': '行政部'}]
"""

 

这篇关于Django 执行sql python 执行sql的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!