python 連mysql數(shù)據(jù)庫

2020-05-09

一、cmd -> pip install?PyMySQL

python3要用PyMySQL

遇到的困難:

1.pip 如果沒設(shè)過環(huán)境變量啥的,要在C:\python\Scripts 這個路徑下執(zhí)行

2.pip?install?PyMySQL 報錯:

(下面這段網(wǎng)上拷的,反正類似的)

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,內(nèi)容:

[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=“你的數(shù)據(jù)庫地址”, user=“用戶名”,password=“密碼”,database=“數(shù)據(jù)庫名”,charset=“utf8”)

2. 使用 cursor() 方法創(chuàng)建一個游標對象 cursor

cursor = conn.cursor()

3. 定義要執(zhí)行的SQL語句

sql ="""select * from xxx;"""

4. 執(zhí)行SQL語句

cursor.execute(sql)

5. 使用 fetchone() 方法獲取單條數(shù)據(jù)

data = cursor.fetchone()

print ("xxx : %s " % data)

6.關(guān)閉光標對象

cursor.close()

7.關(guān)閉數(shù)據(jù)庫連接

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.倆日期天數(shù)相減,發(fā)現(xiàn)str的要轉(zhuǎn)一下類型

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 轉(zhuǎn) datetime.date, 要先將str轉(zhuǎn)datetime,再轉(zhuǎn)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.倆日期相減,輸出結(jié)果要加.days

https://blog.csdn.net/xidianbaby/article/details/97789615

n= (d_date - PERIOD_DATE).days

print(n)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容