python操作MySQL数据库

pip install pymysql
import pymysql

connt=pymysql.connect(host='118.24.3.40',user='jxz',password='123456',
port=3306,db='jxz',charset='utf8',autocommit=True)
cur=connt.cursor()#建立游标
# cur.execute('select * from nhy;')#执行sql,没有返回结果
sql='insert into nhy(name,password) value("xuzhongtao","1234567");'
cur.execute(sql)
# connt.commit()
cur.execute('select * from nhy where name="xuzhongtao";')
print(cur.fetchall())#获取查询到的所有结果
# print(cur.fetchone())#只获取一条
# print(cur.fetchmany(2))#指定获取几条
cur.close()#游标关闭
connt.close()#关闭连接
def my_db(ip,user,passwd,db,sql,port=3306,charset='utf8'):
conn=pymysql.connect(host=ip,user=user,
password=passwd,db=db,
port=port,charset=charset,autocommit=True)
cur=conn.cursor()
cur.execute(sql)
sql=sql.strip()
sql_start=sql[:6].lower()
if sql_start.startswith('select') or sql_start.startswith('show'):
data=cur.fetchall()
else:
return 'ok'
cur.close()
conn.close()
return data
----------------------------------------------------------------------------------------------
import pymysql
import xlwt

conn=pymysql.connect(host='118.24.3.40',user='jxz',password='123456',db='jxz',port=3306,charset='utf8',autocommit=True)
cur=conn.cursor()
# cur=conn.cursor(cursor=pymysql.cursors.DictCursor)#指定游标类型
cur.execute('select * from app_student limit 10;')
# print(cur.description)#表的信息
fildes=[filed[0] for filed in cur.description]#获取到所有的字段
# print(fildes)
data=list(cur.fetchall())#data只是给你假数据,并不会返回数据
data.insert(0,fildes)
print(data)
book=xlwt.Workbook(encoding='utf-8')
sheet=book.add_sheet('sheet1')#
line=0#行号
for d in data:
col = 0 # 列号
for col_data in d:
sheet.write(line,col,col_data)
col+=1
line+=1
# for index,line_data in enumerate(data):
# #['id','name','sex']
# for index2,col_data in enumerate(line_data):
# #0,id
# #1,name
# sheet.write(index,index2,col_data)
# #0,0,id
book.save('nhy.xls')


# print(cur.fetchall())
cur.close()
conn.close()
posted @ 2019-08-03 19:01  taotao12  阅读(199)  评论(0编辑  收藏  举报