Python 数据库连接 excel 读写 日期
1、连接数据库:
import pymysql
db = pymysql.connect("localhost","username","password","database_name")
cursor = db.cursor **获得数据库游标**
**写sql语句**
sql = """ create table aaa(
id int auto_increment primary key**,**
name tinytext**,**
phonenum tinytext**,**
........
zi float**,**
shengri date**,**
dizhi tinytext
)"""
**使用变量传递数据**
sql = " insert into tablename( col1,col2,col3) values('%s','%s','%s')"%(变量1,变量2,变量3)
**执行sql语句**
cursor.execute(sql)
**获取最后一行自增id数,只能在向数据库提交前**
id_lastnum = cursor.lastrowid
**向数据库提交**
db.commit()
**关闭游标和数据库**
cursor.close()
db.close()
**查询**
select aaa from tablename
select * from tablename where aaa =(< >) '值'
**更新数据**
update set colname = "aaa" from tablename where riqi < (curdate()) 将日期小于今天的colname列的值,更新为aaa
2、使用xlrd xlwt读写excel
import xlrd
import xlwt
**打开excel**
xl=xlrd.open_workbook("path")
**根据下标读取表**
sheet = xl.sheets()[0]
**根据表名读取表**
sheet = xl.sheet_by_name("sheet1")
**获取行数和列数**
rows = sheet.nrows
cols = sheet.ncols
**读取行(row),列(col)**
row = sheet.row_values(0) 读取第一行的值
row = sheet.row(0) 读取第一行的值类型和内容
row = sheet.row_types(0) 读取第一行的数据类型
row = sheet.row_values(0,3,6) 读取第一行,第3列到第6列,不包括第6列
**读取指定单元格**
aa = sheet.cell(0,1).value 读取第一行,第二列的值
**行或列求和**
import numpy as np
aa = sheet.rows(0)
country1 = aa[1:] 去除第一列
a1= np.max(country1)#最大值
a2= np.min(country1)#最小值
a3= np.sum(country1)#求和
a4= np.mean(country1)#均值
a5= np.std(country1) #标准差
a6= np.var(country1) #方差
a7= np.median(country1) #中值
**关闭工作表**
xl.close()
3、日期:
from datetime import date
from datetime import datetime
**获取当前时间**
timenow = datetime.datetime.now()
datetody = date.isoformat(timenow)
**Mysql数据库日期函数**
date() 日期
now() 当前日期和时间
curdate() 当前日期
浙公网安备 33010602011771号