<>准备工作

* 安装好了python
* 安装好了pycharm,你安装其他的软件也可以,只要能跑,我安装的是pycharm
<>整体流程

<>安装pymysql

在命令窗口中输入
pip install pymysql
<>连接数据库

connect的参数

* user:就是你的用户名,默认是root
* password:就是你的密码
* host:写到这里我才发现我不知道这东西叫做什么,默认是localhost
* database:你要连接的数据库的名称,可以不写,不写就是None
* port:端口号,默认是3306 import pymysql if __name__ == '__main__': connect = pymysql
.connect( user="root", # The first four arguments is based on DB-API 2.0
recommendation. password="你的密码", host="localhost", #默认是这个 database="test",
#连接的数据库名称,可以不写,不写就是None port=3306)#你的端口号,默认是3306 #
这些东西不用记忆,pycharm中按住Ctrl键点击connect里面有 cursor = connect.cursor() sentence =
"insert into pratice(sname,sid,sgender) values('张三',11,'男')" #增加一名记录 cursor.
execute(sentence) connect.commit() cursor.close() connect.close()# 关闭连接
<>实现增删改查部分
import pymysql def get_connec(): connect = pymysql.connect( user="root", # The
first four arguments is based on DB-API 2.0 recommendation. password="你的密码",
host="localhost", database="atguigudb", port=3306, ) return connect def change(
sql,IsUpdata =False): conn = get_connec() cursor = conn.cursor() coutn = cursor.
execute(sql) conn.commit() if IsUpdata: return cursor.lastrowid else: return
coutn cursor.close() conn.close() #def add(sql): # return
change(sql,IsUpdata=True) #def delete(sql): # return change(sql) #def
updata(sql): # return change(sql) if __name__ == '__main__': connect =
get_connec() # sql = "insert into countries(country_id,country_name,region_id)
values('AN','China',3)" # add(sql) # sql = "delete from countries where
country_id='AN' " # # delete(sql) # sql = "update countries set country_name =
'CHINA' where country_id='AN'" # updata(sql) sql = "select * from countries"
cursor= connect.cursor() #我暂时把这个理解为鼠标 cursor.execute(sql) #
print(cursor.fetchone()) #拿到一个数据 # print(cursor.fetchall()) #拿到全部 print(cursor.
fetchmany(25)) #从第一条数据拿到第25条数据 connect.commit() cursor.close() connect.close()
<>代码中的东西

* connect.cursor()返回一个cursor对象,这个对象的方法包括两大类:1.执行命令,2.接收返回值
* fetchone()拿到一条数据
* fetchall() 拿到全部数据
* fetchmany(n)从第一条数据拿到第n条数据
* commit表示提交数据,

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信