安裝
> pip install PyMySQL
不能使用
pip install MySQL-Python
, 不支持python3归粉, 會(huì)報(bào)錯(cuò)需要visual studio14.
使用
import pymysql
conn = pymysql.connect(host="localhost", user="root", passwd="pass", db="world" )
cur = conn.cursor()
cur.execute( "DROP TABLE IF EXISTS filelist" )
sql = """CREATE TABLE filelist( handle INT UNIQUE,
filename TEXT,
datetime DATETIME,
duration INT)"""
cur.execute( sql )
cur.execute( "INSERT INTO filelist VALUES( '%d', '%s', '%s', 10 ) % ( 1, "sample.mp4", "2019-07-03 18:04:30" ) )
cur.commit()
cur.execute( "SELECT * from filelist" )
for r in cur:
print r
cur.close()
conn.close()
- connect()中db的參數(shù)是要連接的數(shù)據(jù)庫(kù)名字;
- 要執(zhí)行sql語(yǔ)句晰韵,要先獲取到cursor仰迁;
- 當(dāng)有多行SQL語(yǔ)句時(shí)双谆,用""" """把語(yǔ)句引起來(lái)佃扼,可以不用換行時(shí)yoga轉(zhuǎn)義字符衷蜓;
- 當(dāng)執(zhí)行INSERT這類對(duì)數(shù)據(jù)庫(kù)有改變的語(yǔ)句是,需要commit()判呕,否則不生效倦踢;
- 當(dāng)有變量要取值來(lái)插入時(shí),格式為
"INSERT INTO filelist VALUES( '%d', '%s', '%s', 10 ) % ( 1, "sample.mp4", "2019-07-03 18:04:30" )
; - 當(dāng)SQL有DATETIME的數(shù)據(jù)類型時(shí)侠草,可以用string作為input辱挥;
Python中DateTime的使用
from datetime import datetime
day = datetime( 2018, 1, 1, 8, 20, 30)
print( str(day))
使用datetime
lib中的datetime
類;
str(day)得到的string格式為"2019-07-03 18:39:20"
DateTime加減
from datetime import timedelta
time = time + timedelta( minutes=10)
timedelta的參數(shù)可以有 days, hours, minutes等边涕,可以很方便的進(jìn)行時(shí)間加減晤碘。