pymysql的操作:
pymysql操作mysql:
import pymysql
### 连接数据库的参数
conn=pymysql.connect(host='localhost',user='root',password='123qwe',database='test',charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) ### 返回的值是字典类型
sql = "select * from userinfo"
cursor.execute(sql)
res = cursor.fetchmany(12) ### 制定获取多少条数据 返回的是列表套字典
print(res) ### 元组类型 ((1, 'zekai', 1), (2, 'xxx', 2), (3, 'zekai1', 3))
cursor.close()
conn.close()
pymysql的sql注入:
import pymysql
user = input('输入用户名:').strip()
pwd = input('输入密码:').strip()
#### 接下来对用户输入的值进行检验
### 连接数据库的参数
conn=pymysql.connect(host='localhost',user='root',password='123qwe',database='test',charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) ### 返回的值是字典类型
sql = "select * from user where name=%s and password=%s"
cursor.execute(sql, (user, pwd))
res = cursor.fetchall() ###取出所有的数据 返回的是列表套字典
print(res)
cursor.close()
conn.close()
if res:
print('登录成功')
else:
print('登录失败')
pymysql增加数据:
import pymysql
### 连接数据库的参数
conn=pymysql.connect(host='localhost',user='root',password='123qwe',database='test',charset='utf8')
# cursor = conn.cursor() ### 默认返回的值是元祖类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) ### 返回的值是字典类型
sql = "insert into user (name, password) values (%s, %s)"
cursor.execute(sql, ('dshadhsa', 'dbsjabdjsa')) ### 新增一条数据
print(cursor.lastrowid) ### 获取最后一行的ID值
conn.commit()
cursor.close()
conn.close()
pymysql修改数据:
import pymysql
### 连接数据库的参数
conn=pymysql.connect(host='localhost',user='root',password='123qwe',database='test',charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) ### 返回的值是字典类型
sql = "update user set name=%s where id=%s"
cursor.execute(sql, ('dgsahdsa', 2))
conn.commit()
cursor.close()
conn.close()
pymysql删除数据:
import pymysql
### 连接数据库的参数
conn=pymysql.connect(host='localhost',user='root',password='123qwe',database='test',charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) ### 返回的值是字典类型
sql = "delete from t3 where id=%s"
cursor.execute(sql, (1,))
conn.commit()
cursor.close()
conn.close()
pymysql插入300万条数据:
import pymysql
### 连接数据库的参数
conn=pymysql.connect(host='localhost',user='root',password='123qwe',database='test2',charset='utf8')
# cursor = conn.cursor() ### 默认返回的值是元祖类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) ### 返回的值是字典类型
sql = "insert into user (name, email) values (%s, %s)"
data = []
for i in range(3000000):
info = ('zekai'+str(i), 'zekai' + str(i) + '@qq.com' )
data.append(info)
cursor.executemany(sql, data) ### 新增多条数据
conn.commit()
cursor.close()
conn.close()