可视化工具Navicat的使用/pymysql模块的使用

一.可视化工具Navicat的使用

1.官网下载:http://www.navicat.com/en/products/navicat-for-mysql

2.网盘下载:http://pan.baidu.com/s/1bpo5maj

3.须要掌握的基本操做:

  View Code

PS:在生产环境中操做MySQL数据库仍是推荐使用命令工具mysql,但咱们本身开发测试时,可使用可视化工具Navicat,以图形界面的形式操做MySQL数据库python

二.pymysql模块的使用

1.pymysql的下载和使用

以前咱们都是经过MySQL自带的命令行客户端mysql来操做数据库,那如何在python程序中操做数据库呐?这就用到了pymysql模块,该模块的本质就是一个套接字客户端软件,使用前须要事先安装mysql

(1).pymysql模块的下载

pip3 install pymysql

(2).pymysql的使用(数据库和数据都已存在)

  View Code

2.execute()之sql注入

#最后那一个空格,在一条sql语句中若是select * from userinfor where username = "wahaha" -- asadsadf" and pwd = "" 则--以后的条件被注释掉了(注意--后面还有一个空格)

#1.sql注入之:用户存在,绕过密码
wahaha" -- 任意字符
#2.sql注入之:用户不存在,绕过用户与密码
xxx" or 1=1 -- 任意字符

(1).解决方法:

#原来是咱们本身对sql字符串进行拼接
#sql = "select * from userinfo where username='%s' and pwd='%s'" %(user, pwd)
#print(sql)
#result = cursor.execute(sql)

#该写为(execute帮咱们作好的字符串拼接,咱们无需且必定不要再为%s加引号了)
sql = "select * from userinfor where name = %s and password = %s"    #注意%s须要去掉引号,由于pymysql会自动帮咱们加上
result = cursor.execute(sql,[user,pwd])    #pymysql模块自动帮咱们解决sql注入的问题,只要咱们按照pymysql的规矩来

3.增,删,改: conn.commit()

commit()方法: 在数据库里增,删,改的时候,必需要进行提交,不然插入的数据不生效sql

import pymysql
#链接
conn = pymysql.connect(host = "localhost", port = 3306, user = "root", password = "", db = "db8", charset = "utf8")

#建立游标
cursor = conn.cursor()

# #增:
# sql = "insert into userinfor(name,pwd) values (%s,%s)"
# ope_data = cursor.execute(sql,(user,pwd))
#
# #同时插入多条数据
# # cursor.executemany(sql,[("乳娃娃","111"),("爽歪歪","222")])
# print(ope_data)

# #删
# sql = "delete from userinfor where id = 2"
# ope_data = cursor.execute(sql)
# print(ope_data)

# #改
# user = input("输入新的用户名:")
# sql = "update userinfor set name = %s where id = 4"
# ope_data = cursor.execute(sql,user)
# print(ope_data)

#必定要记得commit
conn.commit()

#关闭游标
cursor.close()
#关闭链接
conn.close()

4.查:fetchone,fetchmany,fetchall

fetchone():获取下一行数据,第一次为首行
fetchall():获取全部行数据源
fetchmany(4):获取4行数据

(1).表中内容

(2).使用fetchone():

  View Code

(3).使用fetchall():

  View Code

默认状况下,咱们获取到的返回值是一个元组,只能看到每行的数据,殊不知道没列表明的是什么,这个时候可使用如下方式来返回字典,每行的数据都会生成一个字典:数据库

#返回字典
#在实例化的时候,将属性cursor设置为pymysql.cursors.DictCursor
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

在fetchone示例中,在获取行数据的时候,能够理解开始的时候,有一个行指针指着第一行的上方,获取一行,它就向下移动一行,因此当行指针到最后一行的时候,就不能再获取到行的内容,因此咱们可使用以下方法来移动行指针:ide

cursor.scroll(1,mode='relative')  # 相对当前位置移动
cursor.scroll(2,mode='absolute') # 相对绝对位置移动
第一个值为移动的行数,整数为向下移动,负数为向上移动,mode指定了是相对当前位置移动,仍是相对于首行移动
  View Code

(4).使用fetchmany():

import pymysql conn = pymysql.connect(host = "localhost", port = 3306, user = "root", password = "", db = "db8", charset = "utf8") cursor = conn.cursor(cursor = pymysql.cursors.DictCursor) sql = "select * from userinfor" cursor.execute(sql) #获取两条数据 rows = cursor.fetchmany(2) print(rows) #关闭游标 cursor.close() #关闭链接 conn.close() # 结果: [{'id': 1, 'name': 'wahaha', 'pwd': '123'}, {'id': 2, 'name': '冰红茶', 'pwd': '111'}]
View Code

 

 

 

给你们推荐一位博主,他写的很认真:https://www.cnblogs.com/rixian/工具

相关文章
相关标签/搜索