Python读取数据库写入TXT中(一条数据写入一个TXT文本)

    技术2022-07-11  97

    import os import pymysql conn = pymysql.connect( host='localhost', user='root', password='123456', db='news', charset='utf8', # autocommit=True, # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。 ) def selecttable(): # **************************数据库查询***************************** cur = conn.cursor() sql3 = "select * from zh_new limit 100;" #新闻的条数 result = cur.execute(sql3) # 默认不返回查询结果集, 返回数据记录数。 print(result) for i in range(100): path_list = ['news', str(i) + '.txt'] x=cur.fetchone() print(x[0]) #新闻标题 print(x[1]) #新闻内容 head = '' for path in path_list: head = os.path.join(head, path) print(head) with open(head,"w",encoding='UTF-8') as file: #”w"代表着每次运行都覆盖内容 file.write(x[0] + " 内容:" + x[1]+"\n") # 4. 关闭游标 cur.close() # 5. 关闭连接 conn.close() if __name__=='__main__': selecttable()
    Processed: 0.013, SQL: 9