一、安装

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. PHP7 MongDB 安装与使用

    我们使用 pecl 命令来安装: /usr/local/php7/bin/pecl install mongodb 执行成功后,会输出以下结果: …… Build process completed ...

  2. 关于mysql设置外键,实现参照性完整性约束,以及workbench上的一个bug(?)

    一.本次数据库中有student,course,sc表,其设置情况 -- 创建course表 CREATE TABLE `course` ( `cno` ) NOT NULL, `cname` ) D ...

  3. kylin cubing algorithm(算法)

    看到这一块的视频,结合光方博客的一些文档及自己的一点理解,记个笔记,以备不时之需. by layer cubing 1.on MR  这个算法的对cube的计算就像它的名字一样是按player进行的. ...

  4. Error: no override found for 'vtkRenderWindow'

    VSK7.1+QT5.10环境下报该错误,应该在mainwindow.cpp中添加如下语句 记住,是在mainwindow.cpp中添加,不是在main.cpp中添加:

  5. 使用JBolt新建Maven版工程步骤

    一.打开新建对话框 在左侧右键new中可以找到JFinal创建工程的菜单 JBoltHome页面也有快捷按钮用来弹出创建工程对话框. 二.填写Maven和其他信息配置 填写工程name 主包名 下面有 ...

  6. javascript常见问题总结

    1.const obj = {a:6}; obj.b=8; obj.a=9;//obj为{a:9,b:8};const定义对象的时候是可以改变内容的. const b = "hello&qu ...

  7. (转)Unity_什么是Draw Call? 什么是Batch?

    開發遊戲時,一定被時時提醒要減少 Draw Call,當然UNITY也不例外,打開Game Window裡的 Stats,可以看到 Draw Call 與 Batched 的數字.但到底甚麼是 Dra ...

  8. jquery 蔚蓝网

    $(document).ready(function(){ //提交表单 $("#registerBtn").click(function(){ var email=documen ...

  9. ifconfig 网卡 下面的参数

    ifconfig  eth1 eth1 Link encap:Ethernet HWaddr 20:12:07:04:05:00 inet addr:172.16.77.174 Bcast:172.1 ...

  10. 1.1.27 word表格里的文字不显示

    1.问题: 下载其他人做的表格后,在表格内打字,字不显示. 2.解决方案: 产生这种问题的原因是,该表格设置的字体,你的电脑未安装. a.将隐藏文字选中,设为[宋体]或其他已经安装字体. b.下载[方 ...