python第二节笔记

发布于 2019-12-11  420 次阅读


2019-12-11(if)

 

2019-12-12 (assert,循环,函数)

2019-12-16

2019-12-17

 ##使用python去操作数据库

>>> import MySQLdb
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named MySQLdb
>>> import MySQLdb
>>> 
>>> ##上面报错是因为没有安装这个模块:pip install mysql-python

###连接数据库

##python3的写法
>>> db=MySQLdb.connect(host='localhost',user='root',passsword='qweasdzxc',database='taobao')
##python2的写法(主要的区别是db和passwd)
>>> db=MySQLdb.connect(host='localhost',user='root',passwd='qweasdzxc',db='taobao')  
>>> #等价于
... 
>>> db=MySQLdb.connect('localhost','root','qweasdzxc','taobao')
>>> #等价于
...
>>> DATABASE = {'host':'localhost','db':'taobao','user':'root','passwd':'qweasdzxc','charset':'utf8mb4'}      
>>> db=MySQLdb.connect(**DATABASE) 

##注意:如果数据库出现了中文,需要定义charset,根据自己的数据库结构来定义

操作数据库(cursor)

>>> ##游标
... 
>>> cursor=db.cursor()
>>> sql='select * from tqk_ad;'
>>> cursor.execute(sql)
2L
>>> results=cursor.fetchall()
>>> results
((39L, u'\u624b\u673a', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 1), (37L, u'\u7535\u8111', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 0))
>>> 
>>> for row in results:
...     print(row)
... 
(39L, u'\u624b\u673a', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 1)
(37L, u'\u7535\u8111', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 0)
>>> ##其他更,删,查,等,就sql不同,其他一样,都是用cursor

2019-12-18