欲善其事,必先利其器。那么第一步,我们先下载第三方库。在这里,我使用pymysql库。下载库:在命令行输入pipinstallpymysql进行下载,查看是否下载成功。直接在命令行输入python然后导库C:\Users\June>pythonPython3.6.3|Anaconda,Inc.|(default,Oct152017,03:27:45)[MSCv.190064bit(AMD64)]onwin32Type"help","copyright","credits"or"license"fororeinformation.>>>importpymysql>>>看到这个画面就说明下载成功了,接下来学习如何操作数据库吧!!!连接数据库importpymysql#连接数据库db=pymysql.connect(host='127.0.0.1',user='root',passwd='yourpassword',db='news',port=3306,charset='utf8')上面参数是必填的host:这个是ip地址,因为我这里是本地的,所以填127.0.0.1,你也可以填localhost。user:用户名,如果你也是本地的,就填rootpasswd:这个是密码,你自己的密码填就行了db:这个是数据库名,这里我选择news数据库端口:这个是本地端口一般3306charset:这个是编码方式,一定要和你数据库的编码方式一致。否则连接失败,连接成功。如何验证?这里我们可以选择查看一条数据try:db=pymysql.connect(host='127.0.0.1',user='root',passwd='yourpassword',db='news',port=3306,charset='utf8')#检查数据库是否连接成功cursor=db.cursor()#这是执行sql语句,返回受影响的条数data=cursor.execute('SELECT*FROM`new`')#获取一条数据one=cursor.fetchone()print(data)print(one)exceptpymysql.Errorase:print(e)print('操作数据库失败')finally:#如果连接成功,则数据库必须关闭ifdb:db.close()代码解读:因为在连接数据库的时候,有时候会出现连接失败等异常,所以这里我们捕获异常,这里的异常都是在pymsql.Error中。看不懂上面的代码也没关系,因为接下来我会说,如果运行后有结果,就证明连接成功了。使用后一定要记得关闭数据库连接,防止资源泄露。查询数据importpymysqltry:conn=pymysql.connect(host='127.0.0.1',user='root',passwd='password',db='news',charset='utf8',port=3306)#this它是一个游标,用来操作数据库语句cursor=conn.cursor()#执行sql语句cursor.execute('SELECT*FROM`new`')print(cursor.fetchone())#closecursorcursor.close()除了pymysql。Errorase:print(e)print('Failedtooperatethedatabase')finally:ifconn:conn.close()代码解释:cursor():这是一个游标,用来执行mysql语句,同样需要关闭使用后。excute():这是执行语句,执行参数的mysql语句。fetchone():这个是查看执行语句后的一段数据。fetchall():这个是查看所有的数据。查询数据后,返回一整条数据。有什么办法吗?以字典形式查询呢?快来试试吧!print(cursor.fetchone()['name'])Traceback(mostrecentcallast):File"E:/anaconda/python_project/mysql_test/test2.py",line8,inprint(cursor.fetchone()['name''])TypeError:tupleindicesmustbeintegersorslices,notstr检查了一下,编译器想都没想就给了我这个错误,说这是一个元组,不能这样操作。虽然python没有提供,但是我们可以手动将其转换成字典进行查询。游标这里有一个属性:描述。得到的是数据库中各个字段的情况,如下:print(cursor.description)#下面是结果(('id',3,None,11,11,0,False),('type',253,None,5,5,0,False),('title',253,None,50,50,0,False),('content',253,None,2000,2000,0,False),('view_count',3,None,11,11,0,False),('release_time',12,None,19,19,0,False),('author',253,None,20,20,0,True),('from',253,None,20,20,0,True),('is_valibale',3,None,11,11,0,False)因此我们利用这个属性手动生成一个dictionary#将一段数据转换成字典容易找到new=dict(zip([x[0]forxincursor.description],[xforxincursor.fetchone()]))print(new)#下面是结果{'id':2,'type':'NBA','title':'考辛斯跟腱撕裂赛季报销浓眉詹姆斯金发声祝福','content':'他遭遇跟腱撕裂离开了跟腱,将缺席本赛季余下的比赛,这对于考辛斯和鹈鹕来说无疑是非常重要的半兽人sareamajorhit','view_count':3560,'release_time':datetime.datetime(2018,1,27,12,10),'author':'xiaoylin','from':'腾讯体育','is_valibale':1}这里用zip函数和列表生成公式成功生成一行代码,用字典查询,现在可以打印(new['title'])#下面是结果Cousins跟腱报销撕赛季,浓眉詹皇送上祝福,不过以上只是一个数据,如果有多个呢?那么上面的方法就不行了。这时候就需要用到map函数defnew2dict(new):returndict(zip([x[0]forxincursor.description],[xforxinnew]))news_list=list(map(new2dict,cursor.fetchall()))print(news_list)#下面是结果[{'id':2,'type':'NBA','title':'考辛斯'跟腱撕裂赛季报销,浓眉大王詹姆斯给了自己blessing','content':'他的左脚跟腱撕裂,将缺席本赛季余下的比赛。这对考辛斯和鹈鹕来说无疑是一个重大打击','view_count':3560,'release_time':datetime.datetime(2018,1,27,12,10),'author':'xiaoylin','from':'腾讯体育','is_valibale':1},{'id':3,'type':'NBA','title':'火箭21分,哈登浓眉被骂大帽子太尴尬了','content':'火箭客场113-115不敌鹈鹕,终结4连胜。詹姆斯-哈登34分钟16投5中,其中三分球9投仅1中,罚球14投12中。他得到23分、11次助攻、5个篮板和4次失误。尴尬-12分','view_count':7520,'release_time':datetime.datetime(2018,1,27,12,5),'author':'youngcao','from':'腾讯体育','is_valibale':1},{'id':4,'type':'英超','title':'足总杯-曼联4-0联赛两队晋级桑神首秀两球','content':'2017-18赛季足总杯第4轮,曼联客场4-0击败英乙球队约维尔,成功晋级下一轮。桑切斯迎来曼联处子秀两球','view_count':6560,'release_time':datetime.datetime(2018,1,27,5,49),'author':'ricazhang','from':'腾讯体育','is_valibale':1},{'id':5,'type':'PremierLeague','title':'这是红魔的7号!桑神大腿级首秀回应嘘声质疑','content':'今晨对阵约维尔的首秀同样值得期待。虽然出场72分钟没有进球,但1次助攻和6次威胁传球的数据还是非常可观','view_count':2760,'release_time':datetime.datetime(2018,1,27,6,13),'author':'yaxinhao','from':'腾讯体育','is_valibale':1}]这里巧妙的利用了map函数,因为可以迭代多条数据,需要去操作每一条数据,所以可以想到map函数。接下来我们使用面向对象的方式查询数据库pythonimportpymysqlclassMysqlSearch(object):defget_conn(self):'''连接mysql数据库'''try:self.conn=pymysql.connect(host='127.0.0.1',user='root',passwd='yourpassword',port=3306,charset='utf8',db='news')exceptpymysql.Errorase:print(e)print('无法连接到数据库')defclose_conn(self):'''关闭数据库'''try:ifself.conn:self.conn.close()exceptpymysql.Error:print(e)print('未能关闭数据库')defget_one(self):'''查询一条数据'''try:#这是连接数据库self.get_conn()#查询语句sql='SELECT*FROM`new`WHERE`type`=%s'#这个游标用于执行sql语句cursor=self.conn.cursor()cursor.execute(sql,('PremierLeague',))new=cursor.fetchone()#返回一个字典,方便用户按数据类型new_dict获取数据=dict(zip([x[0]forxincursor.description],new))#关闭游标cursor.close()self.close_conn()returnnew_dictexceptAttributeErrorase:print(e)returnNonedefget_all(self):'''获取所有结果'''sql='SELECT*FROM`new`'self.get_conn()try:cursor=self.conn.cursor()cursor.execute(sql)news=cursor.fetchall()#将数据转成字典,让用户根据key查找数据news_list=list(map(lambdax:dict(zip([x[0]forxincursor.description],[dfordinx])),news))#这样也可以,连续使用两个list生成news_list=[dict(zip([x[0]forxincursor.description],row))forrowinnews]cursor.close()self.close_conn()returnnews_listexceptAttributeError:print(e)returnNonedefmain():#获取一条数据news=MysqlSearch()new=news.get_one()ifnew:print(new)else:print('操作失败')#获取多个数据条news=MysqlSearch()rest=news.get_all()ifrest:print(rest)print(rest[7]['type'],rest[7]['title'])print('type:{0},title:{1}'.format(rest[12]['type'],rest[12]['title']))forrowinrest:print(row)else:print('Nodatawasobtained')if__name__=='__main__':main()这样,database可以通过example的方式查询。我们也可以根据页数查询指定的数据条数defget_more(self,page,page_size):'''查了多少页,查了多少条数据'''offset=(page-1)*page_sizesql='SELECT*FROM`new`LIMIT%s,%s'尝试:self.get_conn()cursor=self.conn.cursor()cursor.execute(sql,(offset,page_size,))news=[dict(zip([x[0]forxincursor.description],new))fornewincursor.fetchall()]cursor.close()self.close_conn()returnnewsexceptAttributeErrorase:print(e)returnNonedefmain():#获取一个页面的数据news=MysqlSearch()new=news.get_more(3,5)ifnew:forrowinnew:print(row)else:print('获取数据失败')if__name__=='__main__':main()使用了mysql的limit关键字,还有其他的,比如对排序分组感兴趣的可以尝试往数据库中添加数据自己defadd_one(self):sql='INSERTINTO`new`(`title`,`content`,`type`,`view_count`,`release_time`)VALUE(%s,%s,%s,%s,%s)'try:self.get_conn()cursor=self.conn.cursor()cursor.execute(sql,('title','content','type','1111','2018-02-01'))cursor.execute(sql,('Title','Content','Type','0000','2018-02-01'))#事务必须提交,否则不显示,只会占用数据库self.conn.commit()return1exceptAttributeErrorase:print('Error:',e)return0exceptTypeErrorase:print('Error:',e)#如果出现错误,提交就是提交正确的语句#self.conn.commit()#下面的方法如果出现异常则不能提交,但如果语句执行成功,它会占据位置self.conn.rollback()return0finally:cursor.close()self.close_conn()defmain():news=OperateSQL()ifnews.add_one():print('添加数据成功')else:print('出现异常,请检查!!!')if__name__=='__main__':main()因为是添加数据,所以需要提交事务,这就需要conn.commit()来提交。添加数据后,如果没有提交,数据库不会显示,修改的数据和删除的数据也不会发布。对,把上面sql变量的语句改成修改或删除的语句即可。如果还是不会,建议练习