MYSQL笔记-pymysql

pymysql操作数据库

import pymysql
# connect 参数包括 主机 用户 密码 数据库 端口 编码方式等
conn = pymysql.connect(host='localhost',user='root',password='123456',database='db_lianxi',charset='utf8')
cursor = conn.cursor()
user = input()
pswd = input()

# 自己进行字符串拼接容易造成SQL注入,
# # sql = "select * from tb1 where username ='%s'and password ='%s'"%(user,pswd)
# 因此可以让pymysql自己拼接字符串,采取下面两种方式
#######1#########
sql = "select * from tb1 where username ='%s'and password ='%s'"
# r :返回SQl语句影响的数据表行数
r = cursor.execute(sql,[user,pswd])
#######2#########
sql = "select * from userinfo where username= %(u)s and password= %(p)s"
r = cursor.execute(sql,{'u':user,'p':pswd})


# *******增删改*******#
sql = "insert into userinfo(username,password) values(%s,%s)"
# 可以一次性增加多条数据
r = cursor.executemany(sql,[('lq','123'),('jjy','456')])
sql = "delete from userinfo where username = %sand password = %s"
sql = "update userinfo set username=%s,password=%s"
# 增删改之后需要提交事务
conn.commit()


# *******查*******#
# 默认是元组类型 为了便于查看应使用字典类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 可以移动游标当前的位置
# 相对当前位置
cursor.scroll(1,'relative')
# 相对绝对位置
cursor.scroll(2,'absolute')
# 只有查询会返回数据行,返回数据行数可以指定
result = cursor.fetchone()
result = cursor.fetchall()
result = cursor.fetchmany(4)


# 最后需要将游标和连接关闭
cursor.close()
conn.close()

猜你喜欢

转载自www.cnblogs.com/lovejjy/p/11924116.html