mysql python 交互
一、安装
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 交互的更多相关文章
- MySQL——python交互
与python交互之前我们需要安装一个MySQL的驱动模块Connector,这个驱动模块直接在cmd命令行输入 pip install mysql.connector 安装是否成功可以接着输入 py ...
- mysql及python交互
mysql在之前写过一次,那时是我刚刚进入博客,今天介绍一下mysql的python交互,当然前面会把mysql基本概述一下. 目录: 一.命令脚本(mysql) 1.基本命令 2.数据库操作命令 3 ...
- MysQL使用一与Python交互
与python交互 在熟练使用sql语句的基础上,开始使用python语言提供的模块与mysql进行交互 这是我们在工作中大事要做的事 先学会sql是基础,一定要熟练编写sql语句 安装引入模块 安装 ...
- MySQL 存储引擎、锁、调优、失误与事务回滚、与python交互、orm
1.存储引擎(处理表的处理器) 1.基本操作 1.查看所有存储引擎 mysql> show engines; 2.查看已有表的存储引擎 mysql> show create table 表 ...
- 开发使用mysql的一些必备知识点整理(四)与python交互
与python交互 在熟练使用sql语句的基础上,开始使用python语言提供的模块与mysql进行交互 这是我们在工作中大事要做的事 先学会sql是基础,一定要熟练编写sql语句 安装引入模块 安装 ...
- MySQL和Python交互
与Python交互 python3模块名:pymysql conda install pymysql conda install sqlalchemy python2模块名:MySQLdb impor ...
- 【呕心总结】python如何与mysql实现交互及常用sql语句
9 月初,我对 python 爬虫 燃起兴趣,但爬取到的数据多通道实时同步读写用文件并不方便,于是开始用起mysql.这篇笔记,我将整理近一个月的实战中最常用到的 mysql 语句,同时也将涉及到如何 ...
- 7.与python交互
与python交互 在熟练使用sql语句的基础上,开始使用python语言提供的模块与mysql进行交互 这是我们在工作中大事要做的事 先学会sql是基础,一定要熟练编写sql语句 安装引入模块 安装 ...
- 工大助手(C#与python交互)
工大助手(爬虫--C#与python交互) 基本内容 工大助手(桌面版) 实现登陆.查成绩.计算加权平均分等功能 团队人员 13070046 孙宇辰 13070003 张帆 13070004 崔巍 1 ...
随机推荐
- 2.7 while 、for 循环控制语句
一.while语句: 在程序中,需要重复性的做某件事: 1.1.1 while: public class Test{ public static void main(String[] args){ ...
- SVN命令备忘录
批量添加(先添加再上传) svn st | grep '^\?' | tr '^\?' ' ' | sed 's/[ ]*//' | sed 's/[ ]/\\ /g' | xargs svn add ...
- ROS * 了解xacro的编写
在urdf文件中,会有很多内容是一样的,当要改变这些语句重某一个相同的参数时却要更改很多次,很吗发,于是有了一种精简化.可复用.模块化的描述形式——xacro 废话少说 声明重复使用的常量 <? ...
- 学习笔记CB006:依存句法、LTP、n元语法模型、N-最短路径分词法、由字构词分词法、图论、概率论
依存句法分析,法国语言学家L.Tesniere1959年提出.句法,句子规则,句子成分组织规则.依存句法,成分间依赖关系.依赖,没有A,B存在错误.语义,句子含义. 依存句法强调介词.助词划分作用,语 ...
- 从零开始在iPhone上运行视频流实时预测模型应用,只需10步
1、买一台苹果电脑,建议MacBook Pro. 2、安装Xcode. 3、克隆TensorFlow:https://github.com/tensorflow/tensorflow.git 4、下载 ...
- SQL server 建立标后,执行代码添加外键
alter table dbo.student add constraint FK_tstudent_class foreign key(classno) references dbo.class(c ...
- 正则替换HTML里的style属性
一个网友问: <p class="a" style="font-size: 12pt; font-family: ""; color: red ...
- Flutter 常用命令
Flutter 常用命令: Flutter 常用命令 说明 flutter 列出所有的命令 flutter help 查看具体命令的帮助信息 flutter doctor 查看是否还需要安装其它依赖 ...
- JIT(Just in time,即时编译,边运行边编译)、AOT(Ahead Of Time,运行前编译),是两种程序的编译方式
JIT(Just in time,即时编译,边运行边编译).AOT(Ahead Of Time,运行前编译),是两种程序的编译方式
- wakatime记录 coding时间的工具
想记录下自己每天coding 的时间以及每个在各个项目上coding的时间,之前一直也没有什么好的办法,无意之间发现wakatime这个插件可以记录自己每天有效的coding时间. wakatime ...