python与mysql交互_mysql与Python交互

ubantu中安装mysql模块(包)

sudo apt-get install python-mysqldb(或py-mysqldb)连上网直接在终端敲就完了

在文件中引入模块

import Mysqldb

Connection对象

用于建立与数据库的连接

创建对象:调用connect()方法

conn=connect(参数列表)

参数host:连接的mysql主机,如果本机是'localhost'

参数port:连接的mysql主机的端口,默认是3306

参数db:数据库的名称

参数user:连接的用户名

参数password:连接的密码

参数charset:通信采用的编码方式,默认是'gb2312',要求与数据库创建时指定的编码一致,否则中文会乱码

对象的方法

close()关闭连接

commit()事务,所以需要提交才会生效

rollback()事务,放弃之前的操作

cursor()返回Cursor对象,用于执行sql语句并获得结果

Cursor对象

执行sql语句(insert,updata···)

创建对象:调用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获得当前连接对象

增加

创建testInsert.py文件,向学生表中插入一条数据(ubantu中安装pycharm)

1 #encoding=utf-8

2 importMySQLdb import *3 try:4 conn=connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')#这句话创建了一个connect对象,connect是MySQLdb包中的一个类,host是要连接的ip,port是连接的端口db指的是要操作哪个数据库,这里要操作名叫test的数据库5 cs1=conn.cursor()#建立一个cursor对象,#connect和cursor是MySQL中的两个py文件即两个类6 sql = 'insert into students(name) values('张良')' #向表student中添加一条名叫张良的数据7 cs1.execute(sql) #执行这条添加语句,execute是cursor中的一个方法

8 conn.commit() #让这个改变生效9 cs1.close() #有开有关10 conn.close()11 exceptException,e:12 print e.message

修改

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

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

删除

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

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

sql语句参数化(数据安全性)

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

1 #encoding=utf-8

2 importMySQLdb3 try:4 conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')5 cs1=conn.cursor()6

7 name=raw_input("请输入学生姓名:")8 params=[name]9 count=cs1.execute('insert into students(name) values(%s)',params)#这个%s就是占位的,不管什么数据类型都用%s,execute的第二个参数要求是一个列表

10 printcount11

12 conn.commit()13 cs1.close()14 conn.close()15 exceptException,e:16 print e.message

其它语句

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

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

查询一行数据

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

1 #encoding=utf8

2 from MysqlHelper import *

3

4 sql='insert into students(sname,gender) values(%s,%s)'

5 sname=raw_input("请输入用户名:")6 gender=raw_input("请输入性别,1为男,0为女")7 params=[sname,bool(gender)]8

9 mysqlHelper=MysqlHelper('localhost',3306,'test1','root','mysql')10 count=mysqlHelper.insert(sql,params)11 if count==1:12 print 'ok'

13 else:14 print 'error'

查询多行数据

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

cur.execute('select * from students')

result=cur.fetchall()

封装

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

创建MysqlHelper.py文件,定义类

1 #encoding=utf8

2 importMySQLdb3

4 classMysqlHelper():5 def __init__(self,host,port,db,user,passwd,charset='utf8'):6 self.host=host7 self.port=port8 self.db=db9 self.user=user10 self.passwd=passwd11 self.charset=charset12

13 defconnect(self):14 self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)15 self.cursor=self.conn.cursor()16

17 defclose(self):18 self.cursor.close()19 self.conn.close()20

21 def get_one(self,sql,params=()):22 result=None23 try:24 self.connect()25

26 self.cursor.execute(sql, params)27 result =self.cursor.fetchone()28

29 self.close()30

31 exceptException, e:32 printe.message33 returnresult34

35 def get_all(self,sql,params=()):36 list=()37 try:38 self.connect()39

40 self.cursor.execute(sql,params)41 list=self.cursor.fetchall()42

43 self.close()44

45 exceptException,e:46 printe.message47 returnlist48

49 def insert(self,sql,params=()):50 return self.__edit(sql,params)51

52 def update(self, sql, params=()):53 return self.__edit(sql, params)54

55 def delete(self, sql, params=()):56 return self.__edit(sql, params)57

58 def __edit(self,sql,params):59 count=060 try:61 self.connect()62 count=self.cursor.execute(sql,params)63 self.conn.commit()64 self.close()65 exceptException,e:66 printe.message67 return count

View Code

添加

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

1 #encoding=utf8

2 from MysqlHelper import *

3

4 sql='insert into students(sname,gender) values(%s,%s)'

5 sname=raw_input("请输入用户名:")6 gender=raw_input("请输入性别,1为男,0为女")7 params=[sname,bool(gender)]8

9 mysqlHelper=MysqlHelper('localhost',3306,'test1','root','mysql')10 count=mysqlHelper.insert(sql,params)11 if count==1:12 print 'ok'

13 else:14 print 'error'

查询一个

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

sql='select sname,gender from students order by id desc'

helper=MysqlHelper('localhost',3306,'test1','root','mysql')

helper.get_one(sql)

实例:用户登录

创建用户表userinfos

表结构如下

id

uname

upwd

isdelete

注意:需要对密码进行加密

如果使用md5加密,则密码包含32个字符

如果使用sha1加密,则密码包含40个字符,推荐使用这种方式

create table userinfos(

id int primary key auto_increment,

uname varchar(20),

upwd char(40),

isdelete bit default 0

);建一个用户表

加入测试数据

插入如下数据,用户名为123,密码为123,这是sha1加密后的值

insert into userinfos values(0,'123','40bd001563085fc35165329ea1ff5c5ecbdbbeef',0);

接收输入并验证

创建testLogin.py文件,引入hashlib模块、MysqlHelper模块

接收用户输入

根据用户名查询,如果未查到则提示用户名不存在

如果查到则匹配密码是否相等,如果相等则提示登录成功

如果不相等则提示密码错误

1 #encoding=utf-8

2 from MysqlHelper importMysqlHelper3 from hashlib importsha14

5 sname=raw_input("请输入用户名:")6 spwd=raw_input("请输入密码:")7

8 s1=sha1()9 s1.update(spwd)10 spwdSha1=s1.hexdigest()11

12 sql="select upwd from userinfos where uname=%s"

13 params=[sname]14

15 sqlhelper=MysqlHelper('localhost',3306,'test1','root','mysql')16 userinfo=sqlhelper.get_one(sql,params)17 if userinfo==None:18 print '用户名错误'

19 elif userinfo[0]==spwdSha1:20 print '登录成功'

21 else:22 print '密码错误'

View Code

验证:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值