pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/5/18
import pymysql
# 创建连接
conn = pymysql.connect(host='192.168.56.11',port=3306,user='db01',passwd='db01',db='db01',charset='utf8')
# 创建游标
cursor = conn.cursor()
# 游标设置为字典类型
# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 执行SQL,并返回影响行数
effect_row = cursor.execute("insert into tb01(id,stu_name) VALUES(2,'wanyongzhen');")
effect_row = cursor.execute("select * from tb01;")
print(effect_row)
# row_1 = cursor.fetchone() # 获取一条数据
# row_2 = cursor.fetchmany(3) # 获取多条数据
# row_3 = cursor.fetchall() # 获取所有数据
# 注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
# cursor.scroll(1,mode='relative') # 相对当前位置移动
# cursor.scroll(2,mode='absolute') # 相对绝对位置移动
# 字符串拼接SQL,可以运行,但是禁止此类操作,以免发生SQL注入漏洞
# inp = input('请输入名字:')
# sql = "insert into tb01(id,stu_name) VALUES(2,'%s');" % inp
# cursor.execute(sql)
# 参数传递,必须使用参数的形式
# inp = input('请输入名字:')
# id = 1
# cursor.execute("insert into tb01(id,stu_name) VALUES(%s,%s);",(id,inp))
# 多条数据操作
l = [
(2,'a'),
(3,'b'),
(4,'c')
]
cursor.executemany("insert into tb01(id,stu_name) VALUES(%s,%s);",l)
# 获取最新自增ID
# new_id = cursor.lastrowid
# 打印影响行数
print(effect_row)
# 提交执行确认
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()