python2客户端交互mysql_mysql与python交互

本文介绍了Python2在Ubuntu16.4环境下如何安装mysql模块,并详细讲解了如何使用pymysql进行数据库的连接、增删改查操作,以及如何进行SQL语句参数化和防止注入。同时,通过封装MysqlHelper类简化数据库操作。
摘要由CSDN通过智能技术生成

1、安装mysql模块

python2 ubuntu16.4环境下安装

先安装依赖,否则安装mysql-python失败

sudo apt-get install libmysqlclient-dev

安装mysql-python

pip install mysql-python

python3 ubuntu16.4环境下安装

安装pip3,pip是python2使用的,pip3是python3使用的

sudo apt install python3-pip

#安装pymysql模块

pip3 install pymysql

安装mysql模块,windows和ubuntu

1c9dd8a221cb

image.png

1c9dd8a221cb

image.png

在文件中引入模块,注意大小写

import pymysql

2、交互类型

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()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组

fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回

scroll(value[,mode])将行指针移动到某个位置

mode表示移动的方式

mode的默认值为relative,表示基于当前行移动到value,value为正则向下移动,value为负则向上移动

mode的值为absolute,表示基于第一条数据的位置,第一条数据的位置为0

对象的属性:

rowcount只读属性,表示最近一次execute()执行后受影响的行数

connection获得当前连接对象

3、增删改

创建testInsert.py文件,向学生表中插入一条数据

import pymysql

try:

conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',

passwd='123',charset='utf8')

cs1=conn.cursor()

count=cs1.execute("insert into students(sname) values('张良')")

print(count)

conn.commit()

cs1.close()

conn.close()

except Exception,e:

print(e)

创建testUpdate.py文件,修改学生表的一条数据

#encoding=utf-8

import pymysql

try:

conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',

passwd='123',charset='utf8')

cs1=conn.cursor()

count=cs1.execute("update students set sname='刘邦' where id=6")

print(count)

conn.commit()

cs1.close()

conn.close()

except Exception,e:

print(e)

创建testDelete.py文件,删除学生表的一条数据

#encoding=utf-8

import pymysql

try:

conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',

passwd='123',charset='utf8')

cs1=conn.cursor()

count=cs1.execute("delete from students where id=6")

print(count)

conn.commit()

cs1.close()

conn.close()

except Exception as e:

print(e)

sql语句参数化:可以防注入

创建testInsertParam.py文件,向学生表中插入一条数据

#encoding=utf-8

import pymysql

try:

conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',

passwd='123',charset='utf8')

cs1=conn.cursor()

sname=input("请输入学生姓名:")

params=[sname]

count=cs1.execute('insert into students(sname) values(%s)',params)

print(count)

conn.commit()

cs1.close()

conn.close()

except Exception as e:

print(e)

其它语句:

cursor对象的execute()方法,也可以用于执行create table等语句

建议在开发之初,就创建好数据库表结构,不要在这里执行

4、查询

创建testSelectOne.py文件,查询一条学生信息

import Pymysql

try:

conn=Pymysql.connect(host='localhost',port=3306,db='test1',user='root',

passwd='123',charset='utf8')

cur=conn.cursor()

cur.execute('select * from students where id=7')

result=cur.fetchone()

print result

cur.close()

conn.close()

except Exception as e:

print(e)

创建testSelectMany.py文件,查询多条学生信息

#encoding=utf8

import Pymysql

try:

conn=Pymysql.connect(host='localhost',port=3306,db='test1',user='root',

passwd='123',charset='utf8')

cur=conn.cursor()

cur.execute('select * from students')

result=cur.fetchall()

print result

cur.close()

conn.close()

except Exception as e:

print(e)

5、封装

观察前面的文件发现,除了sql语句及参数不同,其它语句都是一样的。

创建MysqlHelper.py文件,定义类:

#encoding=utf8

import pymysql

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 as e:

print(e)

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 as e:

print(e)

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 as e:

print(e)

return count

创建testInsertWrap.py文件,使用封装好的帮助类完成插入操作

#encoding=utf8

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')

创建testGetOneWrap.py文件,使用封装好的帮助类完成查询最新一行数据操作

#encoding=utf8

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值