码迷,mamicode.com
首页 > 数据库 > 详细

pymysql 模块

时间:2019-06-29 23:59:09      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:commit   多个   rom   span   sele   word   name   设置   man   

一、查询语句

# 使用pymysql,设计登录
import pymysql
user_name = input(username:)
user_password = input(password:)
conn = pymysql.connect(host=localhost, user=root, password=@WSX3edc, database=db2)  # 连接数据库
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)     # 设置游标卡尺和fetc的格式
sql = "select * from userinfo where username =%s and password = %s"     # sql语句,注意在此次不能用格式化,——在sql语句是注释
cursor.execute(sql, [user_name, user_password])     # list tuple dict
ret = cursor.fetchone()     # 取一个值
# print(ret)
cursor.close()  # 关闭游标卡尺
conn.close()    # 关闭连接
if ret:
    print(登录成功!)
else:
    print(登录失败)
import pymysql
conn = pymysql.connect(host=localhost, user=root, password=@WSX3edc, database=db2)  # 连接数据库
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)     # 设置游标卡尺和fetc的格式
sql = "select * from userinfo limit 3"     # sql语句,分页
cursor.execute(sql)     # list tuple dict
ret = cursor.fetchall()     # 取所有值
print(ret)
cursor.close()  # 关闭游标卡尺
conn.close()    # 关闭连接

 

import pymysql
conn = pymysql.connect(host=localhost, user=root, password=@WSX3edc, database=db2)  # 连接数据库
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)     # 设置游标卡尺和fetc的格式
sql = "select * from userinfo limit 3"     # sql语句,分页

cursor.execute(sql)     # list tuple dict
cursor.scroll(1, mode=absolute)    # 光标到1,默认的模式是相对
ret = cursor.fetchall()     # 取所有值
print(ret)
cursor.close()  # 关闭游标卡尺
conn.close()    # 关闭连接

 

二、插入语句

# 插入一条数据
import pymysql
conn = pymysql.connect(host=localhost, user=root, password=@WSX3edc, database=db2)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "insert into userinfo(username, password) values(%s,%s) "
cursor.execute(sql, [joker, 1234])
conn.commit()   # 提交
cursor.close()
conn.close()
import pymysql
conn = pymysql.connect(host=localhost, user=root, password=@WSX3edc, database=db2)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "insert into userinfo(username, password) values(%s, %s)"
ret = cursor.executemany(sql, [(peter, 123), (talk, 234)])  # 连续添加多个数据,ret 为受影响的行数
conn.commit()
print(ret)
cursor.close()
conn.close()
# 获取自增值
import pymysql
conn = pymysql.connect(host=localhost, user=root, password=@WSX3edc, database=db2)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "insert into userinfo(username, password) values(%s, %s)"
ret = cursor.execute(sql, [talk, 234])  # 连续添加多个数据,ret 为受影响的行数
conn.commit()
print(cursor.lastrowid)     # 获取自增值
print(ret)
cursor.close()
conn.close()

 

pymysql 模块

标签:commit   多个   rom   span   sele   word   name   设置   man   

原文地址:https://www.cnblogs.com/wt7018/p/11108151.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!