pymysql 增删查

 这里是用的ubantu虚拟机连接的win10数据库做的测试。

先附上用的表 结构:demo>>>t1 >>>(id,user,pwd)

mysql> select * from t1;
+----+------+-----+
| id | user | pwd |
+----+------+-----+
|  1 | root | 123 |
|  2 | pig  | 123 |
+----+------+-----+

 


建立链接,总体上分为这几步。 

  1. 建立链接
  2. 拿到游标对象
  3. 执行sql语句
  4. 关闭游标及conn
  5. 注意点(只要对数据产生改动,必须结尾使用conn.commit()才会生效)

1.查询

import pymysql

# 1.建立链接
conn = pymysql.connect(host='192.168.1.105',
                       port=3306,
                       user='huzhen',
                       password='123',
                       database='demo',
                       charset='utf8')
# 2.拿到游标对象
cursor = conn.cursor()


# 3.执行mysql语句
sql = 'select * from t1;'   # 就是一个字符串拼接
rows = cursor.execute(sql)    # rows并不是实际内容,是影响了几行

print(cursor.fetchone())  # 每次查看一条记录,从第一条开始数
print(cursor.fetchmany(2)) # 指定查询多少条记录
print(cursor.fetchall())  # 查询所有

# 4. 关闭游标,关闭conn
conn.close()
cursor.close()

2. 游标移动(和文件操作的seek操作类似)

scroll

# 1. 相对移动,参数(步长,模式)
sursor.scroll(1,mode='relative') 

# 2. 绝对移动,参数(移动到哪个坐标,模式)
sursor.scroll(0,mode='absolute')

3.插入

executemany

# 就是一个字符串拼接
sql = 'insert into t1(user,pwd) values(%s,%s)'   

# 插入的时候在这填参数,在变量sql那填有时候会报错
rows = cursor.execute(sql,('one','123'))    



# 同时插入多条
sql = 'insert into t1(user,pwd) values(%s,%s)' 
rows = cursor.executemany(sql,(('one','123'),('two','123'),('three','123')))  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值