首先引入模块
在py文件中引入pymysql模块
from pymysql import *
Connection 对象
用于建立与数据库的连接
创建对象:调用connect()方法
conn=connect(参数列表)
· 参数host:连接的mysql主机IP,如果本机是'localhost'
· 参数port:连接的mysql主机的端口,默认是3306
· 参数database:数据库的名称
· 参数user:连接的用户名
· 参数password:连接的密码
· 参数charset:通信采用的编码方式,推荐使用utf8
cursor游标对象
cursor1 = con.cursor()
count = cursor1.execute(sql语句) # 返回查到的数据个数
cursor1.fetchone() # 获取一个数据
cursor1.fetchmany(5) # 获取多个数据
cursor1.fetchall() # 获取所有数据
任务结束后关闭cursor,connect
con.close( )
cursor1.close( )
例如:
# 1、导入pymysql from pymysql import * # 2、创建连接对象 con = connect(host= '192.168.205.132',port = 3306,user = 'root', password ='mysql', database = 'School',charset = 'utf8') # 3、创建游标对象 cursor cursors = con.cursor() # 4、执行sql sql = "select * from goods" # 5、执行sql语句 execute:执行 # 返回受影响的行数 count = cursors.execute(sql) # fetch:获取、获得---->get # fetchone一次只拿一条数据 # for i in range(count): # print(cursors.fetchone()) #fetchmany 获取指定条数的数据 # for i in cursors.fetchmany(5): # print(i) # print(cursors.fetchmany(5)) #fetchall 获取全部数据 for i in cursors.fetchall(): print(i) print(count) # 6、关闭游标对象 cursors.close() # 7、关闭连接对象 con.close()
数据的增加删除修改!!!!!!!!!!!
其实很简单,我们只需修改mysql语句
例如插入数据:
sql = "insert into goods_brands values(0,'微软')"
例如修改数据:sql = "update goods_brands set name='内涵段子' where id = 18"
例如删除数据:
sql = "delete from goods_brands where id = 18"
但是注意最后要加上con.commit()把数据提交,这是pymsql的一个功能,防止误操作,只有确认提交才会真正修改数据库