一、安装

sudo apt-get install pymysql

sudo pip3 install pymysql

Connection对象

  • 用于建立与数据库的连接
  • 创建对象:调用connect()方法
  conn=connect(参数列表)
  • 参数host:连接的mysql主机,如果本机是'localhost'
  • 参数port:连接的mysql主机的端口,默认是3306
  • 参数db:数据库的名称
  • 参数user:连接的用户名
  • 参数password:连接的密码
  • 参数charset:通信采用的编码方式,默认是'gb2312',要求与数据库创建时指定的编码一致,否则中文会乱码

对象的方法

  • close()关闭连接
  • commit()事务,所以需要提交才会生效
  • rollback()事务,放弃之前的操作
  • cursor()返回Cursor对象,用于执行sql语句并获得结果

Cursor对象

  • 执行sql语句
  • 创建对象:调用Connection对象的cursor()方法
  cursor1=conn.cursor()

对象的方法

  • close()关闭
  • execute(operation [, parameters ])执行语句,返回受影响的行数
  • fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
  • next()执行查询语句时,获取当前行的下一行
  • fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
  • scroll(value[,mode])将行指针移动到某个位置
    • mode表示移动的方式
    • mode的默认值为relative,表示基于当前行移动到value,value为正则向下移动,value为负则向上移动
    • mode的值为absolute,表示基于第一条数据的位置,第一条数据的位置为0

对象的属性

  • rowcount只读属性,表示最近一次execute()执行后受影响的行数
  • connection获得当前连接对象

二、python 与mysql 连接代码

from pymysql import *
try:
conn=Connection(host="localhost",port=3306,user="root",passwd="mysql",db='python3',charset="utf8")
cursor1=conn.cursor()
sql="insert into students(name) values('郭小二')"
#sql="update students set name= '王小二' where id = 9"
#sql="delete from students shere id=9"
cursor1.execute(sql)
conn.commit()
cursor1.close()
conn.close()
except Exception :
print("错误")

查询:

import MySQLdb
try:
conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')
cur=conn.cursor()
cur.execute('select * from students')
result=cur.fetchall()
print result
cur.close()
conn.close()
except Exception,e:
print e.message

三、sql语句参数化

防止sql注入

from pymysql import *
try:
conn=Connection(host="localhost",port=3306,user="root",passwd="mysql",db='python3',charset="utf8")
cursor1=conn.cursor()
sname=raw_input("请输入学生姓名:")
params=[sname]
cursor1.execute("insert into students(sname) values(%s)",params)
conn.commit()
cursor1.close()
conn.close()
except Exception :
print("错误")

四、封装

import MySQLdb

class MysqlHelper():
def __init__(self,host,port,db,user,passwd,charset='utf8'):
self.host=host
self.port=port
self.db=db
self.user=user
self.passwd=passwd
self.charset=charset def connect(self):
self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)
self.cursor=self.conn.cursor() def close(self):
self.cursor.close()
self.conn.close() def get_one(self,sql,params=()):
result=None
try:
self.connect()
self.cursor.execute(sql, params)
result = self.cursor.fetchone()
self.close()
except Exception, e:
print e.message
return result def get_all(self,sql,params=()):
list=()
try:
self.connect()
self.cursor.execute(sql,params)
list=self.cursor.fetchall()
self.close()
except Exception,e:
print e.message
return list def insert(self,sql,params=()):
return self.__edit(sql,params) def update(self, sql, params=()):
return self.__edit(sql, params) def delete(self, sql, params=()):
return self.__edit(sql, params) def __edit(self,sql,params):
count=0
try:
self.connect()
count=self.cursor.execute(sql,params)
self.conn.commit()
self.close()
except Exception,e:
print e.message
return count

添加

from MysqlHelper import *

sql='insert into students(sname,gender) values(%s,%s)'
sname=raw_input("请输入用户名:")
gender=raw_input("请输入性别,1为男,0为女")
params=[sname,bool(gender)] mysqlHelper=MysqlHelper('localhost',3306,'test1','root','mysql')
count=mysqlHelper.insert(sql,params)
if count==1:
print 'ok'
else:
print 'error'

查询一个

from MysqlHelper import *
sql='select sname,gender from students order by id desc'
helper=MysqlHelper('localhost',3306,'test1','root','mysql')
one=helper.get_one(sql)
print one

mysql python 交互的更多相关文章

  1. MySQL——python交互

    与python交互之前我们需要安装一个MySQL的驱动模块Connector,这个驱动模块直接在cmd命令行输入 pip install mysql.connector 安装是否成功可以接着输入 py ...

  2. mysql及python交互

    mysql在之前写过一次,那时是我刚刚进入博客,今天介绍一下mysql的python交互,当然前面会把mysql基本概述一下. 目录: 一.命令脚本(mysql) 1.基本命令 2.数据库操作命令 3 ...

  3. MysQL使用一与Python交互

    与python交互 在熟练使用sql语句的基础上,开始使用python语言提供的模块与mysql进行交互 这是我们在工作中大事要做的事 先学会sql是基础,一定要熟练编写sql语句 安装引入模块 安装 ...

  4. MySQL 存储引擎、锁、调优、失误与事务回滚、与python交互、orm

    1.存储引擎(处理表的处理器) 1.基本操作 1.查看所有存储引擎 mysql> show engines; 2.查看已有表的存储引擎 mysql> show create table 表 ...

  5. 开发使用mysql的一些必备知识点整理(四)与python交互

    与python交互 在熟练使用sql语句的基础上,开始使用python语言提供的模块与mysql进行交互 这是我们在工作中大事要做的事 先学会sql是基础,一定要熟练编写sql语句 安装引入模块 安装 ...

  6. MySQL和Python交互

    与Python交互 python3模块名:pymysql conda install pymysql conda install sqlalchemy python2模块名:MySQLdb impor ...

  7. 【呕心总结】python如何与mysql实现交互及常用sql语句

    9 月初,我对 python 爬虫 燃起兴趣,但爬取到的数据多通道实时同步读写用文件并不方便,于是开始用起mysql.这篇笔记,我将整理近一个月的实战中最常用到的 mysql 语句,同时也将涉及到如何 ...

  8. 7.与python交互

    与python交互 在熟练使用sql语句的基础上,开始使用python语言提供的模块与mysql进行交互 这是我们在工作中大事要做的事 先学会sql是基础,一定要熟练编写sql语句 安装引入模块 安装 ...

  9. 工大助手(C#与python交互)

    工大助手(爬虫--C#与python交互) 基本内容 工大助手(桌面版) 实现登陆.查成绩.计算加权平均分等功能 团队人员 13070046 孙宇辰 13070003 张帆 13070004 崔巍 1 ...

随机推荐

  1. javascript最全最好的判断数组的方法

    var arr = [1,2,3,1]; var arr2 = [{ abac : 1, abc : 2 }]; function isArrayFn(value){ if (typeof Array ...

  2. 认识Ajax

    1.简介 AJAX 相当于异步 JavaScript 和 XML,是一种用于创建快速动态网页的技术.通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味着可以在不重新加载整个网 ...

  3. 跨域访问技术CORS(Cross-Origin Resource Sharing)简介

    为什么要用CORS? CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing). 它允许浏览器向跨源服务器,发出XMLHttp ...

  4. Linux之prink原理

    我的分析是基于Linux4.15.1 1.看看kernel是如何调用到console初始化函数的: 分两条线: a.start_kernel  -->  console_init   --> ...

  5. freebsd 记录点

    问题一: FreeBSD修改python的默认版本 在/usr/local/bin目录下, mv python python.old ln -s pythonX.X  python in X.X wr ...

  6. Developing avb

    ai automake  ai libtool  ai pkg-config autogen ai libgstreamer1.0-0  ai libgstreamer1.0-dev  ai chec ...

  7. leetcode中的python学习

    list.extend() list1.extend(list2(or string)) 将list2(or string)的所有元素添加到list1中: list1.append(list2(or ...

  8. DOM 基础

    文档对象模型(Document Object Model)是表示和处理一个HTML或XML文档的常用方法 查找 直接查找 var obj = document.getElementById('i1') ...

  9. mq的基本介绍和基本用法

    1.什么是MQ,有什么用? MQ 是message queue ,消息队列,也叫消息中间件,遵守JMS(java message service)规范的一种软件.(同时还有另一个叫AMQP的应用层协议 ...

  10. Python 3 教程

    http://www.runoob.com/python3/python3-tutorial.html https://www.jianshu.com/p/f1332c58ca86