这里是用的ubantu虚拟机连接的win10数据库做的测试。
先附上用的表 结构:demo>>>t1 >>>(id,user,pwd)
mysql> select * from t1;
+----+------+-----+
| id | user | pwd |
+----+------+-----+
| 1 | root | 123 |
| 2 | pig | 123 |
+----+------+-----+
建立链接,总体上分为这几步。
- 建立链接
- 拿到游标对象
- 执行sql语句
- 关闭游标及conn
- 注意点(只要对数据产生改动,必须结尾使用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')))