大家好,我是Python进阶。前言我们在进行Python编程的时候,经常要保存一些数据,其中最方便的就是保存在文本文件中。但是,如果保存的文件太大,使用文本文件是不切实际的。毕竟,打开它是一个问题。这时候,我们就需要用到数据库了。说到数据库,相信大多数人都不陌生。今天我们要学习的是我认为是数据库中最好的Mysql数据库。1.下载并导入模块为了让Python能够与Mysql进行交互,我们这里需要使用到Pymsql模块。下载模块:pipinstallpymysql导入模块:importpymysql2.创建数据库打开数据库连接软件SqlYong,如图:输入命令:CREATEDATABASEIFNOTEXISTSpeople;因此创建了一个人员数据库。3、创建数据表并写入数据USEpeople;CREATETABLEIFNOTEXISTSstudent(idINTPRIMARYKEYAUTO_INCREMENT,NAMECHAR(10)UNIQUE,scoreINTNOTNULL,timDATETIME)ENGINE=INNOBASECHARSETutf8;插入学生(NAME,score,tim)VALUES('fasd',60-0,622-01')SELECT*FROMstudent;通过以上操作,创建了一张数据表Student,并向其中写入数据,结果如下:我们可以删除插入的数据,一行代码:TRUNCATEstudent;4.会下载MySQL和Python的连接图中参数依次填写初始化参数,db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')这样people就连接上了数据库,可以看到连接成功的打印信息:可以看到我们打印了Mysql版本和Host信息。五、创建一个游标进行操作1.创建一个游标cur=db.cursor2.写一个插入数据的表达式sql="INSERTIINTOstudent(NAME,score,tim)VALUES('任性的90后男孩',100,now())"3.打开游标事件cur.begin()4.执行数据库语句,异常判断try:cur.execute(sql)执行数据库语句exceptExceptionase:print(e)db.rollback()异常发生并且游标回滚操作else:db。commit()最后提交数据库操作:cur.close()关闭游标db.close()关闭数据库5.执行插入操作数据库建立后,我们就可以向其中插入数据了。importtimedb=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')cur=db.cursor()db.begin()sql="INSERTINTOstudent(NAME,score,tim)VALUES('%s',%d,'%s')"data=('HW',90,tt)try:cur.execute(sql%data)exceptExceptionase:print(e)db.rollback()else:db.commit()finally:cur.close()db.close()这样数据就可以插入进去了。我们也可以自定义插入:importpymysqlimporttimett=time.strftime('%Y-%m-%d%H:%M:%S',time.localtime(time.time()))db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')cur=db.cursor()db.begin()s=input('string:')d=input('number:')sql="INSERTINTTOstudent(NAME,score,tim)VALUES('%s','%s','%s')"try:data=(s,d,tt)cur.execute(sql%data)exceptExceptionase:print(e)db.rollback()else:db.commit()finally:cur.close()db.close()另外我们还可以同时插入多条数据,只要先定义获取所有的数据,然后再调用即可。这里需要使用函数Exec??utemany来插入多条数据。这里我插入10万条数据,测试插入时间。步骤如下:importpymysqlimporttimestart=time.time()tt=time.strftime('%Y-%m-%d%H:%M:%S',time.localtime(time.time()))db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')cur=db.cursor()db.begin()sql="insertintostudent(NAME,score,tim)values(%s,%s,%s)"defget():ab=[]foryinrange(1,100000):ify>=100:data=('user-'+str(y),str(str(float('%.f'%(y%100)))),tt)else:data=('user-'+str(y),str(y),tt)ab.append(data)returnabtry:data=get()cur.executemany(sql,data)exceptExceptionase:print(e)db.rollback()else:db.commit()finally:print('完成插入数据')cur.close()db.close()end=time.time()print('timeused:',str(end-start))6.执行update操作有些数据我们认为是过时的,如果你想改变它,你必须更新它的数据importtimedb=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')cur=db.cursor()db.begin()sql="updatestudentsetname='zjj'wherescore=100"当分数为100时,将名称改为zjjtry:cur.execute(sql%data)exceptExceptionase:print(e)db.rollback()else:db.commit()最后:cur。关闭()db.close()7。执行删除操作有时候如果有些数据对我们没有影响,我们可以删除它,这里是删除数据表中的一条记录。importpymysqldb=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')cur=db.cursor()db.begin()sql="deletefromstudentwherename='fasd';"当名称等于'fasd'时删除这条记录try:cur.execute(sql)exceptExceptionase:print(e)db.rollback()else:db.commit()finally:cur.close()db.close()也可以删除表中的所有数据,只需将Sql语句改为:sql='TRUNCATEstudent;'当然也可以删除表,但一般不建议这样做,以免误删:DROPTABLEIFEXISTSstudent;8.执行查询操作有时我们需要查询数据库中的数据,Python可以轻松帮助我们。importpymysqlimporttimett=time.strftime('%Y-%m-%d%H:%M:%S',time.localtime(time.time()))db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')cur=db.cursor()db.begin()sql="select*fromstudent;"try:cur.execute(sql)res=cur.fetchall()查询数据库中的数据foryinres:print(y)打印数据库中标记的所有数据,以元组的形式exceptExceptionase:print(e)db.rollback()else:db.commit()finally:cur.close()db.close()6.总结我们在抓取网页的时候,需要保存大量的数据。这时候数据库就派上用场了,可以更方便快捷的保存数据。
