1、这里使用PyQt5中内置数据库连接mysql方法
self.db = QSqlDatabase.addDatabase('QMYSQL') # 数据库设置
self.db.setHostName('localhost')
self.db.setDatabaseName('bigpeng')
self.db.setUserName('root')
self.db.setPassword('')
if not self.db.open():
QMessageBox.critical(None, ('无法打开数据库'), ('无法建立连接,需要配置'), QMessageBox.Cancel)
return False
query = QSqlQuery()
query.exec("select * from df_grounddata where tu_place='大棚一'")
filename = 'data.csv'# 导出为csv文件
with open(filename, mode='w', encoding='utf-8') as f:
write = csv.writer(f, dialect='excel')
write.writerow(['时间', '位置','土壤深度','温度', '湿度'])# 先写下标题
while query.next():
date = query.value(1).toString('yyyy-MM-dd HH:mm:ss')
place = query.value(4)
depth = query.value(5)
shidu = query.value(6)
wendu = query.value(7)
write.writerow([date,place,depth,shidu,wendu])# 每次写一行
2、使用Python连接数据库mysql方法
import pymysql
import csv
def from_mysql_get_all_info():
conn = pymysql.connect(
host='xxxxxx',
port=3306,
user='xxxx',
db=xx',
password='xxxxx',
charset='utf8mb4'
cursor = conn.cursor()
sql = 'select * from py.tencent_news'
cursor.execute(sql.encode('utf-8'))
data = cursor.fetchall()
conn.close()
return data
def write_csv():
data = from_mysql_get_all_info()
filename = 'data/corpus.csv'#文件名和路径
with open(filename,mode='w',encoding='utf-8') as f:
write = csv.writer(f,dialect='excel')
for item in data:
write.writerow(item)
write_csv()