2020-05-09
一、cmd -> pip install PyMySQL
python3要用PyMySQL
遇到的困难:
1.pip 如果没设过环境变量啥的,要在C:\python\Scripts 这个路径下执行
2.pip install PyMySQL 报错:
(下面这段网上拷的,反正类似的)
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None))
after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAI
LED] certificate verify failed (_ssl.c:661)'),)
解决方法:
https://blog.csdn.net/yunxiaobaobei/article/details/95997407
https://www.dancoder.cn/article/75
在C:\Users\x x x x\ 新建文件夹pip,文件夹里新建文件pip.ini,内容:
[global]
index-url = http://pypi.douban.com/simple
trusted-host = pypi.douban.com
disable-pip-version-check = true
timeout = 120
[list]
format = columns
然后再试pip install PyMySQL,直接成功了,厉害啊。。。
二、python中连接mysql
https://www.cnblogs.com/chongdongxiaoyu/p/8951433.html
https://www.runoob.com/python3/python3-mysql.html
1. 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
2. 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
3. 定义要执行的SQL语句
sql ="""select * from xxx;"""
4. 执行SQL语句
cursor.execute(sql)
5. 使用 fetchone() 方法获取单条数据
data = cursor.fetchone()
print ("xxx : %s " % data)
6.关闭光标对象
cursor.close()
7.关闭数据库连接
conn.close()
遇到的问题:直接print(data)报must be str, not tuple
改为:print(str(data)),返回:(datetime.date(2020, 5, 9),) 嗯。。。怪
然后改成print(data[0][0]),可以了。。。输出是%Y-%m-%d(2020-05-10)格式
2.俩日期天数相减,发现str的要转一下类型
unsupported operand type(s) for -: 'str' and 'datetime.date'
https://blog.csdn.net/df_1818/article/details/82756485
https://zhidao.baidu.com/question/2074033297914585068.html (方法1好使)
str 转 datetime.date, 要先将str转datetime,再转datetime.date
d_datetime = time.strptime(d,'%Y-%m-%d')
year,month,day = d_datetime[:3]
d_date = datetime.date(year,month,day)
print(d_date, type(d_date))
3.俩日期相减,输出结果要加.days
https://blog.csdn.net/xidianbaby/article/details/97789615
n= (d_date - PERIOD_DATE).days
print(n)