day6_mysql模块

mysql数据存在磁盘里,mysql数据库:host是211.149.218.16,端口是3306,用户名是jxz,密码是123456,db也是jxz
import pymysql
connect1 = pymysql.connect(host='211.149.218.16', port=3306, user='jxz', passwd='123456', charset='utf8', db='jxz')  # 连接数据库,必须是utf8,不能是utf-8
cur = connect1.cursor()  # 建立游标,相当于仓库管理员
sql = 'select * from stu limit 3;'
insert_sql = "insert into stu values(99, 'ssj')"
cur.execute(insert_sql)  # 执行sql语句
cur.execute(sql)  # 执行sql语句
res = cur.fetchall()  # 获取所有sql语句执行的结果,fetchone()只能获取一条数据,fetchmany(),传入几条就获取几条
connect1.commit()  # 提交数据
print(res)  # 返回一个元组
for c in cur:
      print(c)  # 直接循环cur对象,可以获取每一条数据,不用fetchone()一条条调
cur.close()  #关闭游标
connect1.close()  # 关闭数据库

 

import pymysql
from pymysql.cursors import DictCursor
connect1 = pymysql.connect(host='211.149.218.16', port=3306, user='jxz', passwd='123456', charset='utf8')  # 连接数据库
cur = connect1.cursor(DictCursor)  # 指定游标类型,返回字典
sql = 'select * from stu limit 2,5;'  # 表示从第3条开始往后读5条数据
cur.execute(sql)
for c in cur:
      print(c)  # 返回值是字典类型,字典好取值

 

def op_mysql(host, user, passwd, db, sql, charset='utf8', port=3306):
import pymysql
from pymysql.cursors import DictCursor
con = pymysql.connect(host=host, user=user, passwd=passwd, db=db, charset=charset, port=port)
cur = con.cursor(DictCursor) # 指定返回数据的类型是字典
cur.execute(sql)
if sql.strip().startswith('select'):
res = cur.fetchall()
else:
con.commit() # 除了查询操作外,其他操作都需要commit(),才能同步到数据库里面
res = 'ok'
cur.close()
con.close()
print(res)
return res
sql1 = 'insert into stu values(100, "insert语句测试");'
sql2 = 'update stu set name = "update语句测试" where id = 77;'
sql3 = 'delete from stu where id = 99;'
sql4 = 'select id,name from stu where id = 999;'
op_mysql(host='211.149.218.16', user='jxz', passwd='123456', db='jxz', sql=sql1)
op_mysql(host='211.149.218.16', user='jxz', passwd='123456', db='jxz', sql=sql2)
op_mysql(host='211.149.218.16', user='jxz', passwd='123456', db='jxz', sql=sql3)
op_mysql(host='211.149.218.16', user='jxz', passwd='123456', db='jxz', sql=sql4)

 

cur.fetchall()  # 它一直返回的是一个二维的list,不管你指定了什么类型的游标
cur.fetchone()  # 它才返回的是具体的值,如果指定游标类型是字典,那么它就返回一个字典,否则返回的是list,如果你写的sql只有一条结果的话,用fetchone方便,如果写的sql结果有多条,那么用fetchall

posted @ 2018-03-09 17:18  laosun0204  阅读(114)  评论(0编辑  收藏  举报