python对Mysql数据库进行操作的实例详解


本文摘自php中文网,作者零下一度,侵删。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

import MySQLdb#引入mysql模块

class ManagerDB:#创建一个类

    def __init__(self):

        self.db=None

        self.cursor=None

        self.connit()

def connit(self):#链接数据库

        self.db=MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='exam_python')

     #host主机名

     #user用户名

     #passwd用户名密码

     #db数据库

        self.cursor=self.db.cursor()

def start(self):#开始

        while True:

            self.menu()#引入菜单栏

            xz=input('请输入要选择的编号:')

if xz==1:

                self.student = self.addStudent()

if xz==2:

                self.showStudent()

if xz==3:

                self.delStudent()

if xz==4:

                print '再见'

                self.db.close()

self.cursor.close()

break

    def addStudent(self):#添加

        sname=raw_input('请输入要添加学生的姓名')

        ssex=raw_input('请输入要添加学生的性别')

        sage=raw_input('请输入要添加学生的年龄')

try:

            sq1="insert into student(name,sex,age)values('%s','%s','%s')"%(sname,ssex,sage)

for i in range(10):

                self.cursor.execute(sq1)

self.db.commit()

print '成功添加10条信息'

        except:

            print '添加失败'

            self.db.rollback()

def showStudent(self):#查看

        self.cursor.execute('select * from student')

print 'id 姓名 性别 年龄'

        for i in self.cursor:

            print i[0],i[1],i[2],i[3]

def delStudent(self):#删除

        try:

            self.cursor.execute('delete from student where id=5')

self.db.commit()

print '成功删除id为5的信息'

        except:

            print '删除失败'

            self.db.rollback()

def menu(self):

        print '''

        ----------------------------

                1 添加信息

                2 显示数据

                3 删除数据

                4 退出系统

        ----------------------------

                '''

if __name__ == '__main__':

    s=ManagerDB()#实例化对象

    s.start()

以上就是python对Mysql数据库进行操作的实例详解的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python对xml文件的读写案例分享

Python如何判断闰年

Python中reduce()函数的示例

Python中type()是什么意思

能够编译运行Python的软件有哪些

Python怎么创建类

Python判断字符类型怎么做

Python如何调用api接口

Python需要什么基础

Python中map()函数的方法示例

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...