最近在学习python爬虫,写一下关于MySQL数据库操作的笔记
有错误的话还请看到的大佬们指正
1.导包
import pymysql
2.链接数据库
conn = pymysql.connect(host='127.0.01',port=3306,
user='root',password='123456')
3.获取游标
cursor=conn.cursor()
4.创建数据库和表
4.1 创建database
cursor.execute('CREATE database if not exists duanzi')
4.2 创建table
cursor.execute('CREATE table IF not exists duanzi.duanzi1 (titile text,tag text,content text)')
- 以下为增删改查操作
5.1 增
# 我要把sss列表数据添加到daunzi数据库中的duanzi1表中
sss=[('123','456','789'),('qwe','asd','zxc')]
cursor.executemany('INSERT INTO daunzi.duanzi1 (title,tag,content) VALUES (%s,%s,%s)’,sss)
5.2、删
# 我要删除daunzi数据库的duanzi1表中 tag为456的一行或多行
cursor.execute('DELETE FROM daunzi.duanzi1 WHER tag=%s','456'
5.3、改
# 我要更改tag为asd的一行数据中的content数据为hxd
cursor.execute('UPDATE duanzi.duanzi1 SET content=%s WHERE tag=%s',('hxd','asd')
5.4、查
cursor.execute('SELECT * FROM duanzi.duanzi1')
t1 = cursor.fetchall() # 查看所有
t2 = cursor.fetchone() # 查看第一行
t3 = cursor.fetchmany(n) # 查看前n行
- 保存修改内容
conn.commit()
- close
cursor.close()
conn.close()
边学边往里加