打印

python数据库编程。

[复制链接]
538|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主


[color=rgba(0, 0, 0, 0.75)][url=]版权[/url]



连接数据库[color=rgba(0, 0, 0, 0.75)]          [color=rgba(0, 0, 0, 0.75)]     
Python数据库编程

创建连接时,就指定:764261140
pymysql.connect(host=’172.25.254.178”, user=’cooffee”,
password=’cooffee”, charset=’utf8’, autocommit=True)
# host(要连接的主机ip), user(用户), passwd(用户密码), charset(默认编码格式),autocommit(对数据库操作是否自动提交)
eg:

[color=rgb(0, 0, 136) !important]import pymysql[color=rgb(136, 0, 0) !important]#连接数据库conn = pymysql.connect(host=[color=rgb(0, 153, 0) !important]'172.25.254.178', user=[color=rgb(0, 153, 0) !important]'cooffee',                password=[color=rgb(0, 153, 0) !important]'cooffee', charset=[color=rgb(0, 153, 0) !important]'utf8', autocommit=[color=rgb(0, 0, 136) !important]True) [color=rgb(136, 0, 0) !important]#创建一个游标, 用来给数据库发送sql语句的cur = conn.cursor()[color=rgb(136, 0, 0) !important]# 选择需要操作的数据库conn.select_db([color=rgb(0, 153, 0) !important]'cooffee')[color=rgb(0, 0, 136) !important]try:    create_sql = [color=rgb(0, 153, 0) !important]'create table myuser (name varchar(30), age int );'    cur.execute(create_sql)   [color=rgb(136, 0, 0) !important]#执行的sql[color=rgb(0, 0, 136) !important]except Exception [color=rgb(0, 0, 136) !important]as e:    print([color=rgb(0, 153, 0) !important]'fail:',e)[color=rgb(0, 0, 136) !important]else:    print([color=rgb(0, 153, 0) !important]'Success')[color=rgb(136, 0, 0) !important]# 4. 先关闭游标cur.close()[color=rgb(136, 0, 0) !important]# 5. 关闭数据库连接conn.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

数据库的增删改查单条记录: 实现思路: sqli='数据库的增删改查语句' cur.execute(isqli)批量实现用:cur.executemany(insert_sqli, users) #users为一个列表
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
记录的增加[color=rgb(0, 0, 136) !important]import random[color=rgb(0, 0, 136) !important]import pymysqlconn = pymysql.connect(host=[color=rgb(0, 153, 0) !important]'172.25.254.178', user=[color=rgb(0, 153, 0) !important]'cooffee',                password=[color=rgb(0, 153, 0) !important]'cooffee', charset=[color=rgb(0, 153, 0) !important]'utf8', autocommit=[color=rgb(0, 0, 136) !important]True)cur = conn.cursor()conn.select_db([color=rgb(0, 153, 0) !important]'cooffee')[color=rgb(0, 0, 136) !important]try:    insert_sqli1 = [color=rgb(0, 153, 0) !important]'insert into myuser VALUES ("user1", 32);'    insert_sqli2 = [color=rgb(0, 153, 0) !important]'insert into myuser VALUES ("user2", 18);'    cur.execute(insert_sqli1)    cur.execute(insert_sqli2)    [color=rgb(136, 0, 0) !important]#批量对数据实现操作    users=[([color=rgb(0, 153, 0) !important]'user'+str(i),random.choice(range([color=rgb(0, 102, 102) !important]18,[color=rgb(0, 102, 102) !important]40))) [color=rgb(0, 0, 136) !important]for i [color=rgb(0, 0, 136) !important]in range([color=rgb(0, 102, 102) !important]10)]    insert_sqli = [color=rgb(0, 153, 0) !important]'insert into myuser VALUES (%s, %s);'    cur.executemany(insert_sqli, users)    select_sqli = [color=rgb(0, 153, 0) !important]'select * from myuser;'    res=  cur.execute(select_sqli)    print([color=rgb(0, 153, 0) !important]"查看语句的返回结果:", res)[color=rgb(0, 0, 136) !important]except Exception [color=rgb(0, 0, 136) !important]as e:    print([color=rgb(0, 153, 0) !important]'fail:',e)[color=rgb(0, 0, 136) !important]else:    print([color=rgb(0, 153, 0) !important]'Success')cur.close()conn.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24


查看表中的数据及更改与删除[color=rgb(0, 0, 136) !important]import pymysqlconn = pymysql.connect(host=[color=rgb(0, 153, 0) !important]'172.25.254.178', user=[color=rgb(0, 153, 0) !important]'cooffee',                password=[color=rgb(0, 153, 0) !important]'cooffee', charset=[color=rgb(0, 153, 0) !important]'utf8', autocommit=[color=rgb(0, 0, 136) !important]True)cur = conn.cursor()conn.select_db([color=rgb(0, 153, 0) !important]'cooffee')[color=rgb(0, 0, 136) !important]try:    delete_sqli = [color=rgb(0, 153, 0) !important]'delete from myuser where name="user3";'    cur.execute(delete_sqli)    update_sqli = [color=rgb(0, 153, 0) !important]'update myuser set age="1" where name="user2";'    cur.execute(update_sqli)    select_sqli = [color=rgb(0, 153, 0) !important]'select * from myuser;'    res = cur.execute(select_sqli)    print([color=rgb(0, 153, 0) !important]"查看语句的返回结果:", res)    [color=rgb(136, 0, 0) !important]# cur.fetchone类似与文件的操作f.readline, 每次只读取一条记录;    print([color=rgb(0, 153, 0) !important]"查找一条记录:", cur.fetchone())    print([color=rgb(0, 153, 0) !important]"查找一条记录:", cur.fetchone())    [color=rgb(136, 0, 0) !important]#cur.fetchmany, 类似于f.readlines, 返回的是一个元组;    print([color=rgb(0, 153, 0) !important]"查找5条记录:",cur.fetchmany([color=rgb(0, 102, 102) !important]5))    [color=rgb(136, 0, 0) !important]#cur.fetchall返回的是一个元组;    print([color=rgb(0, 153, 0) !important]"1查找所有记录", cur.fetchall())    [color=rgb(136, 0, 0) !important]#移动游标的位置, 到记录的最开始    cur.scroll([color=rgb(0, 102, 102) !important]0, mode=[color=rgb(0, 153, 0) !important]'absolute')    print([color=rgb(0, 153, 0) !important]"查找2所有记录", cur.fetchall())    cur.scroll(-[color=rgb(0, 102, 102) !important]3, mode=[color=rgb(0, 153, 0) !important]'relative')    print([color=rgb(0, 153, 0) !important]"查找2所有记录", cur.fetchall())[color=rgb(0, 0, 136) !important]except Exception [color=rgb(0, 0, 136) !important]as e:    print([color=rgb(0, 153, 0) !important]'fail:',e)[color=rgb(0, 0, 136) !important]else:    print([color=rgb(0, 153, 0) !important]'Success')cur.close()conn.close()
  • 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

[color=rgb(0, 0, 136) !important]import pymysqldef create_data():    [color=rgb(136, 0, 0) !important]# 1. 连接数据库, host, user, passwd, charset    conn = pymysql.connect(host=[color=rgb(0, 153, 0) !important]'172.25.254.178', user=[color=rgb(0, 153, 0) !important]'cooffee',                           password=[color=rgb(0, 153, 0) !important]'cooffee', charset=[color=rgb(0, 153, 0) !important]'utf8',                           autocommit=[color=rgb(0, 0, 136) !important]True, db=[color=rgb(0, 153, 0) !important]'cooffee')    [color=rgb(136, 0, 0) !important]# 2. 创建一个游标, 用来给数据库发送sql语句的;    cur = conn.cursor()    [color=rgb(136, 0, 0) !important]# 3. 创建一个表    [color=rgb(0, 0, 136) !important]try:        create_sqli = [color=rgb(0, 153, 0) !important]'create table bankData( id int PRIMARY KEY, ' \                      [color=rgb(0, 153, 0) !important]'name varchar(10), money FLOAT);'        cur.execute(create_sqli)    [color=rgb(0, 0, 136) !important]except Exception [color=rgb(0, 0, 136) !important]as e:        print([color=rgb(0, 153, 0) !important]"Error: 表已经创建", e)    [color=rgb(0, 0, 136) !important]else:        print([color=rgb(0, 153, 0) !important]"表创建成功")    [color=rgb(136, 0, 0) !important]#4. 创建数据    [color=rgb(0, 0, 136) !important]try:        users = [([color=rgb(0, 102, 102) !important]610001, [color=rgb(0, 153, 0) !important]'张三', [color=rgb(0, 102, 102) !important]1000), ([color=rgb(0, 102, 102) !important]610002, [color=rgb(0, 153, 0) !important]'李四', [color=rgb(0, 102, 102) !important]1000),([color=rgb(0, 102, 102) !important]610003, [color=rgb(0, 153, 0) !important]'粉条', [color=rgb(0, 102, 102) !important]1000)]        insert_sqli = [color=rgb(0, 153, 0) !important]'insert into bankData VALUES (%s, %s, %s);'        cur.executemany(insert_sqli, users)    [color=rgb(0, 0, 136) !important]except Exception [color=rgb(0, 0, 136) !important]as e:        print([color=rgb(0, 153, 0) !important]'Error:', e)    [color=rgb(0, 0, 136) !important]else:        print([color=rgb(0, 153, 0) !important]"初始化数据成功!")    [color=rgb(136, 0, 0) !important]# 4. 先关闭游标    cur.close()    [color=rgb(136, 0, 0) !important]# 5. 关闭数据库连接    conn.close()class TransferMoney(object):    def __init__(self, conn):        self.conn = conn        self.cursor = conn.cursor()    def transfer(self, source_accid, target_accid, money):        [color=rgb(0, 153, 0) !important]"""        转账方法:            # 1. source_accid帐号是否存在;            # 2. target_accid帐号是否存在;            # 3. 是否有足够的钱            # 4. source_accid扣钱            # 5. target_acci加钱            # 6. 提交对数据库的操作        :param source_accid: 源帐号id        :param target_accid: 目标帐号id        :param money: 转账金额        :return: bool        """        [color=rgb(136, 0, 0) !important]# 判断帐号是否存在        self.check_account_avaiable(source_accid)        self.check_account_avaiable(target_accid)        [color=rgb(136, 0, 0) !important]# 是否有足够的钱        self.has_enough_money(source_accid, money)        [color=rgb(0, 0, 136) !important]try:            [color=rgb(136, 0, 0) !important]# source_accid扣钱            self.reduce_money(source_accid, money)            [color=rgb(136, 0, 0) !important]#  target_acci加钱            self.add_money(target_accid, money)            self.conn.commit()        [color=rgb(0, 0, 136) !important]except Exception [color=rgb(0, 0, 136) !important]as e:            [color=rgb(136, 0, 0) !important]# ********************撤销对于数据库的更改操作, 回滚******************            self.conn.rollback()        [color=rgb(0, 0, 136) !important]else:            print([color=rgb(0, 153, 0) !important]"%s给%s转账%s成功" %(source_accid, target_accid, money))    def check_account_avaiable(self, accid):        [color=rgb(0, 153, 0) !important]"""判断帐号是否存在, 传递参数为帐号id"""        select_sqli = [color=rgb(0, 153, 0) !important]'select * from bankData where id=%s' %(accid)        print([color=rgb(0, 153, 0) !important]"execute sql:", select_sqli)        res = self.cursor.execute(select_sqli)        [color=rgb(136, 0, 0) !important]# 判断是否能找到帐号为accid的记录;        [color=rgb(0, 0, 136) !important]if res == [color=rgb(0, 102, 102) !important]1:            [color=rgb(0, 0, 136) !important]return  [color=rgb(0, 0, 136) !important]True        [color=rgb(0, 0, 136) !important]else:            [color=rgb(0, 0, 136) !important]raise  Exception([color=rgb(0, 153, 0) !important]"帐号%s不存在" %(accid))    def has_enough_money(self, accid, money):        [color=rgb(0, 153, 0) !important]"""是否有足够的钱"""        select_sqli = [color=rgb(0, 153, 0) !important]'select money from bankData where id=%s' %(accid)        print([color=rgb(0, 153, 0) !important]'execute sql:', select_sqli)        self.cursor.execute(select_sqli)        [color=rgb(136, 0, 0) !important]# 获取查询到的金钱数额        acc_money = self.cursor.fetchone()[[color=rgb(0, 102, 102) !important]0]        print(acc_money, type(acc_money))        [color=rgb(136, 0, 0) !important]# 判断        [color=rgb(0, 0, 136) !important]if acc_money >= money:            [color=rgb(0, 0, 136) !important]return  [color=rgb(0, 0, 136) !important]True        [color=rgb(0, 0, 136) !important]else:            [color=rgb(0, 0, 136) !important]raise  Exception([color=rgb(0, 153, 0) !important]"账户%s没有足够的金额, 当前余额为%s" %(accid, acc_money))    def reduce_money(self, accid, money):        [color=rgb(136, 0, 0) !important]# 对于accid减少的金额为money        [color=rgb(0, 0, 136) !important]try:            update_sqli = [color=rgb(0, 153, 0) !important]'update bankData set money=money-%s where id="%s"' %(money, accid)            print([color=rgb(0, 153, 0) !important]"redcue_money sql:", update_sqli)            self.cursor.execute(update_sqli)        [color=rgb(0, 0, 136) !important]except Exception [color=rgb(0, 0, 136) !important]as e:            print([color=rgb(0, 153, 0) !important]'Error:',e)    def add_money(self, accid, money):        [color=rgb(136, 0, 0) !important]# 对于accid减少的金额为money        [color=rgb(0, 0, 136) !important]try:            update_sqli = [color=rgb(0, 153, 0) !important]'update bankData set money=money+%s where id="%s"' %(money, accid)            print([color=rgb(0, 153, 0) !important]"add_money sql:", update_sqli)            self.cursor.execute(update_sqli)        [color=rgb(0, 0, 136) !important]except Exception [color=rgb(0, 0, 136) !important]as e:            print([color=rgb(0, 153, 0) !important]'Error:',e)    def __del__(self):        [color=rgb(136, 0, 0) !important]# 当删除对象时, 自动执行, 关闭游标;        self.cursor.close()        conn.close()[color=rgb(0, 0, 136) !important]if __name__ == [color=rgb(0, 153, 0) !important]'__main__':    create_data()    conn = pymysql.connect(host=[color=rgb(0, 153, 0) !important]'172.25.254.178', user=[color=rgb(0, 153, 0) !important]'cooffee',                               password=[color=rgb(0, 153, 0) !important]'cooffee', charset=[color=rgb(0, 153, 0) !important]'utf8',                               db=[color=rgb(0, 153, 0) !important]'cooffee')    trans = TransferMoney(conn)    trans.transfer([color=rgb(0, 153, 0) !important]'610003', [color=rgb(0, 153, 0) !important]'610002', [color=rgb(0, 102, 102) !important]100)
  • 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
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122


2. 面向对象,文件操作与数据库操作复习题目:

文件score.dat中保存的是100名学生的姓名和Python课、高数和英语成绩。

(1)定义学生类,其中包含姓名、Python课、高数和英语成绩及总分、均分数据成员,成员函数根据需要确定。

(2)读入这名学生的成绩,用对象列表进行存储。

(3)求出各科和总分的最高分。

(4)请按总分的降序(高成绩在前,低成绩在后)排序

(5)在屏幕上显示各科及总分的最高分,排序后的成绩单(包括总分)保存到文件odered_score.dat中。

(6) 将文件中的所有学生信息, 保存在mariadb数据库中;

[color=rgb(0, 0, 136) !important]import randomdef create_scoredata(filename='score.dat'):    databases=([color=rgb(0, 153, 0) !important]'name'+str(i)+[color=rgb(0, 153, 0) !important]','+str(random.randint([color=rgb(0, 102, 102) !important]0,[color=rgb(0, 102, 102) !important]100))+[color=rgb(0, 153, 0) !important]','+str(random.randint([color=rgb(0, 102, 102) !important]0,[color=rgb(0, 102, 102) !important]100))               +[color=rgb(0, 153, 0) !important]','+str(random.randint([color=rgb(0, 102, 102) !important]0,[color=rgb(0, 102, 102) !important]100)) [color=rgb(0, 0, 136) !important]for i [color=rgb(0, 0, 136) !important]in range([color=rgb(0, 102, 102) !important]100))    [color=rgb(0, 0, 136) !important]with open(filename,mode=[color=rgb(0, 153, 0) !important]"a+") [color=rgb(0, 0, 136) !important]as f:        [color=rgb(0, 0, 136) !important]for items [color=rgb(0, 0, 136) !important]in databases:            f.write(items+[color=rgb(0, 153, 0) !important]'\n')def reade_scoreadata(filename='score.dat'):    [color=rgb(0, 0, 136) !important]with open(filename) [color=rgb(0, 0, 136) !important]as f:        readelise=f.readlines()    [color=rgb(0, 0, 136) !important]return [items[[color=rgb(0, 102, 102) !important]0].split([color=rgb(0, 153, 0) !important]',') [color=rgb(0, 0, 136) !important]for items [color=rgb(0, 0, 136) !important]in [reade.split() [color=rgb(0, 0, 136) !important]for reade [color=rgb(0, 0, 136) !important]in readelise]]class Student(object):    def __init__(self,list):        self.total=[color=rgb(0, 102, 102) !important]0        self.average=[color=rgb(0, 102, 102) !important]0        self.list=list    def Total_average(self):        [color=rgb(0, 0, 136) !important]for items [color=rgb(0, 0, 136) !important]in self.list:            self.total=int(items[[color=rgb(0, 102, 102) !important]1])+int(items[[color=rgb(0, 102, 102) !important]2])+int(items[[color=rgb(0, 102, 102) !important]3])            self.average=self.total/[color=rgb(0, 102, 102) !important]3.0            items.append(self.total)            items.append(self.average)    def max_high(self):        self.python=max([items[[color=rgb(0, 102, 102) !important]1][color=rgb(0, 0, 136) !important]for items [color=rgb(0, 0, 136) !important]in self.list])        self.math=max([items[[color=rgb(0, 102, 102) !important]2][color=rgb(0, 0, 136) !important]for items [color=rgb(0, 0, 136) !important]in self.list])        self.English=max([items[[color=rgb(0, 102, 102) !important]3][color=rgb(0, 0, 136) !important]for items [color=rgb(0, 0, 136) !important]in self.list])        self.total=max([items[[color=rgb(0, 102, 102) !important]4][color=rgb(0, 0, 136) !important]for items [color=rgb(0, 0, 136) !important]in self.list])        print([color=rgb(0, 153, 0) !important]'各科的最高分及总分的最高分:python:%s math:%s English:%s 总分:%s'%(self.python,self.math,self.English,self.total))    def sorte(self):        [color=rgb(0, 0, 136) !important]return sorted(list,key=[color=rgb(0, 0, 136) !important]lambda x:-x[[color=rgb(0, 102, 102) !important]4])def write_data(list,filename='odered_score.dat'):    [color=rgb(0, 0, 136) !important]with open(filename,mode=[color=rgb(0, 153, 0) !important]'w+') [color=rgb(0, 0, 136) !important]as f:        [color=rgb(0, 0, 136) !important]for items [color=rgb(0, 0, 136) !important]in list:            items[[color=rgb(0, 102, 102) !important]4]=str(items[[color=rgb(0, 102, 102) !important]4])            items[[color=rgb(0, 102, 102) !important]5]=str(items[[color=rgb(0, 102, 102) !important]5])            f.write([color=rgb(0, 153, 0) !important]','.join(items)+[color=rgb(0, 153, 0) !important]'\n')[color=rgb(0, 0, 136) !important]if __name__==[color=rgb(0, 153, 0) !important]'__main__':    create_scoredata()    list=reade_scoreadata([color=rgb(0, 153, 0) !important]'score.dat')    student=Student(list)    student.Total_average()    student.max_high()    list1=student.sorte()    write_data(list1)
  • 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



使用特权

评论回复

相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

30

主题

36

帖子

1

粉丝