Pymysql学习

PyMysql学习

创建数据库链接

connection = pymysql.connect(host="127.0.0.1",port=3306,user="root",password="root",
	db="pymysql",
	charset="utf8")

#获取游标
cursor=connection.cursor()

查寻数据库版本

cursor.execute("select version()")

创建数据表操作

cursor.execute(""
	create table user(name varchar(20),passwd varchar(20),age int(10),primary key(name))
	"")

数据库插入操作

//变量方式插入
name,passwd,age="tom","tom",17
sql="insert into user(name,passwd,age) values('%s','%s','%s')"%(name,passwd,age)
cursor.execute(sql)
connection.commit()
//字典方式插入数据
info={"name":"alice","passwd":"alice","age":19}

cursor.execute("insert into user(name,passwd,age) values(%(name)s,%(passwd)s,%(age)s)",info)

connection.commit()

批量执行SQL语句

cursor.executemany(
	'insert into user (name,passwd,age) values (%s,%s,%s)',[
	('uu','uu',14),
	('ww','ww',10),
	])
connection.commit()

数据库查询操作

cursor.execute("select name,passwd from user where name='ww'")

其他操作

#获取查询数据

print(cursor.fetchone())
print(cursor.fetchmany(3))
print(cursor.fetchall())

#游标位置控制
cursor.scroll(1,mode='relative')
cursor.scroll(2,mode='absolute')

#设置游标类型
cursor:默认,元组类型
DictCursor:字典类型
SSCursor:无缓冲元组类型
SSDictCursor:无缓冲字典类型
无缓冲类型适用于数据量大的
原文地址:https://www.cnblogs.com/Mr-l/p/12068650.html