一.python 操作mysql

import pymysql

'''

# 1.基本语法

# (1) 连接数据库

# conn = pymysql.connect(host = "ip地址",user = "用户",password = "密码",database = "数据库",charset = "字符集",port = "端口号")

# 至少填写前4个参数

conn = pymysql.connect(host = "127.0.0.1",user = "root",password="123456",database = "db5",charset="utf8",port=3306)

# (2).创建游标对象,该对象执行sql相关方法

cursor = conn.cursor()

# (3).执行sql语句

sql = "select * from employee"

# (如果是查询,返回查到的所有条数)

res = cursor.execute(sql)

print(res)

# (4) 获取查询出来的数据 fetchone 只获取一条数据

res = cursor.fetchone()

print(res)

#获取当前数据版版本号

res = cursor.execute("select version()")

print(res)

data = cursor.fetchone()

print("版本号",data)

# (5) 释放游标对象

# cursor.close()

# (6) 关闭数据库连接

conn.close()

'''

# 2.创建/删除 数据表

'''

conn = pymysql.connect(host = "127.0.0.1",user = "root",password="123456",database="db5")

# 创建游标对象 通过这个对象操作数据库

cursor = conn.cursor()

sql1 =  """

create table myt10(

id int unsigned primary key auto_increment,

first_name char(10) not null,

last_name char(10) not null,

age int unsigned,

sex tinyint,

money float

)

"""

# 准备sql语句

sql2 = "desc myt9"

# 执行sql语句

# cursor.execute(sql1)

cursor.execute(sql2)

# 获取一条数据

# data = cursor.fetchone()

# 获取所有数据

data = cursor.fetchall()

print(data) #('id', 'int(10) unsigned', 'NO', 'PRI', None, 'auto_increment')

try:

# sql3 = "drop table myt1011111"

sql3 = "drop table myt10"

res = cursor.execute(sql3)

print(res)

except:

pass

print(33344)

# 释放游标对象

cursor.close()

# 关闭远程数据库连接

conn.close()

"""

(

('id', 'int(10) unsigned', 'NO', 'PRI', None, 'auto_increment'),

('first_name', 'char(10)', 'NO', '', None, ''),

('last_name', 'char(10)', 'NO', '', None, ''),

('age', 'int(10) unsigned', 'YES', '', None, ''),

('sex', 'tinyint(4)', 'YES', '', None, ''),

('money', 'float', 'YES', '', None, '')

)

"""

'''

# (3)事务处理

# 1.基本语法

# 连接数据库

conn = pymysql.connect(host = "127.0.0.1",user = "root",password="123456",database = "db5",charset="utf8",port=3306)

# 创建游标对象,该对象执行sql相关方法

cursor = conn.cursor()

# 1 .开启事务  通过pymysql 操作数据库,默认开启事务,需要最后通过commit进行提交数据;

sql1 = "begin"

sql2 = "select * from employee limit 3"

sql3 = "update employee set age = 39 where id = 3"

sql4 = "commit"

cursor.execute(sql1)

cursor.execute(sql2)

cursor.execute(sql3)

# 最终需要通过commit提交事务,提交数据

cursor.execute(sql4)

# 释放游标对象

cursor.close()

# 关闭数据库连接

conn.close()

二.sql注入相关

import pymysql

""""""

# 1.sql 注入的问题

user = input("user>>:").strip()

pwd = input("password>>:").strip()

# sdfsd' or 1=1 -- sfdksjk

conn= pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db5",charset="utf8",port=3306)

cursor = conn.cursor()

sql = "select * from usr_pwd where username = '%s'  and password = '%s' " % (user,pwd)

print(sql) #select * from usr_pwd where username = 'iuiuuyuy' or 1=1 -- sdfsdfs'  and password = ''

res = cursor.execute(sql)

print(res)

if res:

print("登录成功!")

else:

print("登录失败~")

# 释放游标对象

cursor.close()

# 关闭数据库连接

conn.close()

''''''

# 2.解决办法:

# 如果想用execute 的预处理功能 %s 不要在套一层引号了,但是如果是字符串的格式化,必须加引号.

user = input("user>>:").strip()

pwd = input("password>>:").strip()

conn= pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db5",charset="utf8",port=3306)

cursor = conn.cursor()

sql = 'select * from usr_pwd where username = %s  and password = %s '

# execute可以提前过滤sql语句,做一下预处理.方式sql注入.

print(sql)

res = cursor.execute(sql,(user,pwd))

if res:

print("登录成功")

else:

print("登录失败")

# 释放游标对象

cursor.close()

# 关闭数据库连接

conn.close()

三.python 操作mysql 增删改

import pymysql

"""

通过pymysql这个模块提交给mysql 服务器,默认开启事务

事务处理,必须要依赖commit来进行提交数据,也可以用rollback回滚到开始时候 的数据

不提交数据,默认回滚

提交数据 conn.commit()

回滚数据 conn.rollback()

execute executemany 如果执行的是增删改,返回的是受影响的行数

execute 如果执行的是查,返回的是查询到的数量;

"""

# 连接数据库

conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",database="db5")

# cursor=pymysql.cursors.DictCursor 把返回的数据变成字典,默认是元组;

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 1.增

# 执行sql语句

sql = """insert into myt9(first_name,last_name,age,sex,money) values(%s,%s,%s,%s,%s)"""

# execute只执行一条数据

res = cursor.execute( sql,( "马","巨强",74,1,8) )

# print(res)

# executemany执行多条数据 返回第一次插入的那条数据的id

# res = cursor.executemany(  sql, [("张","过程",88,0,2),("意","四",13,1,90),("罗","婷",18,1,100000),("黄","胸大",20,0,900)]  )

# print(res)

# 获取最后一条插入数据的id(一般常用订单号上)

print(cursor.lastrowid)

# 2.删

"""

sql = "delete from myt9 where id = %s "

res = cursor.execute(sql,(5))

if res:

print("删除成功")

else:

print("删除失败")

"""

# 3.改

"""

sql = "update myt9 set first_name = %s where  id = %s"

res = cursor.execute(sql,("王",9))

if res:

print("修改成功")

else:

print("修改失败")

"""

# 4.查 返回搜索的条数

sql2 = "select * from myt9"

res = cursor.execute(sql2)

print(res)

# 查询一条 fetchone()

data = cursor.fetchone()

print(data)

# 查询多条 fetchmany(查询的条数) 默认查一条,基于上一条查询,往下在查查2条

data = cursor.fetchmany(2)

print(data)

# 查询所有数据

data = cursor.fetchall()

print(data)

#[{'id': 9, 'first_name': '王', 'last_name': '巨强', 'age': 74, 'sex': 1, 'money': 8.0}]

for row in data:

first_name = row['first_name']

last_name = row['last_name']

age = row['age']

if row['sex'] == 0:

sex = "男"

else:

sex = "女"

money = row['money']

print("姓:{},名字:{},性别:{},年龄:{},收入:{}".format(first_name,last_name,sex,age,money))

# 可以选择查询的位置

sql3 = "select * from myt9 where id >= 20"

res = cursor.execute(sql3)

print(res)

data = cursor.fetchone()

print(data)

# 相对当前位置进行移动

cursor.scroll(7,mode="relative")  # 向后移动

print(cursor.fetchone())

cursor.scroll(-5,mode="relative") # 向前移动

print(cursor.fetchone())

# 绝对位置移动

cursor.scroll(0,mode="absolute")

print(cursor.fetchone())

conn.commit()

cursor.close()

conn.close()

MySQL 之与Python相关的更多相关文章

  1. redis安装 phpredis Jedis 扩展的实现及注意事项,php,java,python相关插件安装实例代码和文档推荐

    redis安装 phpredis Jedis 扩展的实现及注意事项,php,java,python相关插件安装实例代码和文档推荐 1.Redis 官方网站下载: http://redis.io/dow ...

  2. 【Python五篇慢慢弹(5)】类的继承案例解析,python相关知识延伸

    类的继承案例解析,python相关知识延伸 作者:白宁超 2016年10月10日22:36:57 摘要:继<快速上手学python>一文之后,笔者又将python官方文档认真学习下.官方给 ...

  3. python学习道路(day12note)(mysql操作,python链接mysql,redis)

    1,针对mysql操作 SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpass'); 设置密码 update user set password ...

  4. 计算机开放电子书汇总(包括二十多本python相关的图书教程)

    计算机开放电子书汇总(包括二十多本python相关的图书教程) https://github.com/it-ebooks/it-ebooks-archive 这个汇总包含了各种计算机相关的开放图书和文 ...

  5. 运行easy_install安装python相关程序时提示failed to create process

    运行easy_install安装python相关程序时提示failed to create process,因为安装了两个python,卸载了的那个目录没删除,删除了另外的python目录后这个问题就 ...

  6. 【导航】Python相关

    [博客导航] Python相关导航 [索引]Python常用资源(从新手到大牛) [任务]Python语言程序设计.MOOC学习 [笔记]Python集成开发环境——PyCharm 2018.3下载. ...

  7. 剑指offer用位运算实现两个数相加,及python相关的位操作

    题目:写一个函数,求两个整数之和,要求在函数体内不得使用+.-.*./四则运算符号. 代码: # -*- coding:utf-8 -*-class Solution:    def Add(self ...

  8. python相关资料链接

    后续的博客更新,会涉及到很多的python及python的框架相关的内容,这里将自己收藏的一些关于python相关资料的链接做一个整理,算是一个导航索引吧... PS:其中有些链接对应的技术团队文章, ...

  9. MySQL学习笔记-事务相关话题

    事务机制 事务(Transaction)是数据库区别于文件系统的重要特性之一.事务会把数据库从一种一致状态转换为另一个种一致状态.在数据库提交工作时,可以确保其要么所有修改都已经保存了,要么所有修改都 ...

随机推荐

  1. STM32 MDK C 常见易错点

    1.MDK编译器单字节的负数-1,-2,-3... ... 处理:存储,类型转换,位对齐. char 定义的变量在运算过程尤其类型转换,逻辑比大少会被当做 unsigned char 处理,这里很容易 ...

  2. 【PAT甲级】1078 Hashing (25 分)(哈希表二次探测法)

    题意: 输入两个正整数M和N(M<=10000,N<=M)表示哈希表的最大长度和插入的元素个数.如果M不是一个素数,把它变成大于M的最小素数,接着输入N个元素,输出它们在哈希表中的位置(从 ...

  3. 【JavaWeb】Spring入门——HelloWorld

    0.为什么要使用Spring https://www.cnblogs.com/zmmi/p/7922186.html 1. 下载jar包 https://blog.csdn.net/qq_435401 ...

  4. Linux :ls 命令

    常用命令: ls:列出当前路径下的文件和目录 ls -a:列出当前路径下的所有文件和目录(包括隐藏文件和目录) ls -l:以列表方式显示文件或目录的详细信息 ls -al:可以结合使用 ls xxx ...

  5. NAT-T和PAT(IPSec)

    ¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥NAT-T技术介绍¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥ 为什么TCP和UDP不能穿越:TCP和UDP有一个IP头的尾部校验(校验头部和负载 ...

  6. vue调试工具vue-devtools安装及使用方法

    vue调试工具vue-devtools安装及使用方法 https://www.jb51.net/article/150335.htm 本文主要介绍 vue的调试工具 vue-devtools 的安装和 ...

  7. Java面向对象编程 -1.6

    引用传递与垃圾产生分析 经过了一系列的分析之后已经确认,所有的引用传递的本质就是一场堆内存的调戏游戏.如果对于引用传递如果处理不当那么也会造成垃圾的产生, 那么本次将针对于垃圾产生的原因进行简单分析. ...

  8. Codeforces Round #589 (Div. 2)D(思维,构造)

    #define HAVE_STRUCT_TIMESPEC#include<bits/stdc++.h>using namespace std;vector<int>adj[10 ...

  9. 一份非常值得一看的Java面试题

    包含的模块 本文分为十九个模块,分别是: Java 基础.容器.多线程.反射.对象拷贝.Java Web .异常.网络.设计模式.Spring/Spring MVC.Spring Boot/Sprin ...

  10. java窗口程序字符串时间转成时间戳

    pom.xml 文件: ?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...