pymysql

#pymysql笔记
##pymysql是mysql数据库与Python进行交互的一个模块。
通过数据库mysql进行数据分析
##使用介绍

 
conn = pymysql.connect( # 创建数据库连接
    host='localhost', # 要连接的数据库所在主机ip
    port=30307  #端口号
    user='root',  # 数据库登录用户名
    password='rooot',  # 登录用户密码
     database=“mysql”  #数据库名称
    charset='utf8' # 编码,注意不能写成utf-8
)
cursor = con.cursor()    ##获取光标

然后可以创建表

sql = """
create table book(       #book是表的名称
bookid int auto_increment primary key ,  #bookid、bookname等是表中的列
bookname VARCHAR(255) not null ,
authors VARCHAR(255) not null ,
year_publication YEAR not null
);
cursor.execute(sql)      # 不要忘记了使用光标
"""

接下来就是对表的操作了,包括增加,删除和查询

1、插入数据
execute:一次插入一条记录

cursor.execute('insert into book(bookname, authors, year_publication) values("%s", "%s", %s);' % ('Python从入门到放弃', '乔布斯', 2019))
conn.commit()    #每次都要注意光标,因为在mysql的操作上就是运用光标

2)executemany:一次插入多条记录

data = [
    ('21天完全入门Java', '扎克伯格', 2018),
    ('Linux学习手册', '李纳斯', 2017),
    ('MySQL从删库到跑路', '比尔盖茨', 2018),  #数据要按表中列的格式进行排序
]
cursor.executemany('insert into book(bookname, authors, year_publication) values("%s", "%s", %s);', data)
conn.commit()
 
2、查询数据  fetch
fetch操作包括3个方法,分别是fetchone()、fetchall()、fetchmany()。
fetchone()表示查询一个
fetchmany(x)表示查x行数据  #注意fetchone和fetchmany是按顺序查询的,查询了一条,接下来的就要往下查询了
fetchall()表示查询所有 

cursor.execute('select * from book where bookid < %s;', [4])
books = cursor.fetchall()
print(books)  #要记得输出

3、删除 delete or excutemany
使用pymysql执行插入、更新、删除操作都是相似的,最后都需要commit提交:

cursor.execute('delete from book where bookid=%s;', [1])
conn.commit()
这时候,bookid为1的记录已经被删除,如下图所示:


也可以使用executemany()一次性删除多条:

cursor.executemany('delete from book where bookid=%s;', [[2], [4]])
conn.commit()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值