首页 > 数据库 >python mysql eXCEL

python mysql eXCEL

时间:2023-04-24 14:33:35浏览次数:35  
标签:python mysql eXCEL cursor host sql import amouts data

import re
import pymysql
import requests
from bs4 import BeautifulSoup
import lxml
import sys, io
import openpyxl

# 数据库信息
host = '192.168.56.101'
username = "root"
passwd = "123456"
database = "test"
port = 3306
charset = "utf8"
excel_name = input("输入Excel表格名称:") + ".xlsx"
# 连接数据库创建表
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='UTF8')
db = pymysql.connect(host=host, user=username, password=passwd, database=database)
cursor = db.cursor()
cursor.execute("drop table if exists test001")
sql = 'CREATE TABLE test001(ID int primary key auto_increment,title char(20),amouts char(255))'
cursor.execute(sql)

# 函数 创建文本文档
def mk_file(name):
    return name + ".txt"


# 函数,插入数据
def insert(value):
    db = pymysql.connect(host=host, user=username, password=passwd, database=database, charset="utf8")
    cursor = db.cursor()
    sql = "insert into test001(title,amouts) values(%s,%s)"
    try:
        cursor.execute(sql, value)
        db.commit()
        print("插入数据成功")
    except Exception as e:
        db.rollback()
        print(e)
        print("插入数据失败")


# 函数 生成Excel表格
def wr_Excel(table_name):
    # 连数据库,读取数据
    conn = pymysql.connect(host=host, user=username, password=passwd, database=database, port=3306, charset="utf8")
    cur = conn.cursor()
    sql = "select * from %s;" % table_name
    cur.execute(sql)
    # 使用%s占位符可以占位where条件,但是不能占位表名
    # 实际为了防止sql注入,在where条件使用占位符通常使用下述方法
    # sql = "select * from table_name where %s;"(此时假如要输入的变量为age)
    # cur.execute(sql,age)
    sql_result = cur.fetchall()
    cur.close()
    conn.close()
    # 写Excel
    book = openpyxl.Workbook()
    sheet = book.active
    fff = [filed[0] for filed in cur.description]  # 获取表头信息
    sheet.append(fff)


# 进行流程
newtext = mk_file("text")
data_file = open(newtext, 'w', encoding="UTF8")
with open('C:\\Users\\35548\Desktop\\百度产品大全.html', 'r', encoding='UTF8') as web_data:
    Soup = BeautifulSoup(web_data, 'lxml')
titles = Soup.select('#content > div > div >a')
amouts = Soup.select('#content > div > div >span')
for titles, amouts in zip(titles, amouts):
    data = {
        'titles': titles.get_text(),
        'amouts': amouts.get_text()
    }
    data_str = str(data)
    data_file.write(data_str)
    insert((titles.get_text(), amouts.get_text()))
wr_Excel('test001')

 

标签:python,mysql,eXCEL,cursor,host,sql,import,amouts,data
From: https://www.cnblogs.com/xkdn/p/17349424.html

相关文章

  • mysql8存取json
    1、建表CREATETABLE`test`(`id`bigintNOTNULL,`name`varchar(255)CHARACTERSETutf8mb4COLLATEutf8mb4_0900_ai_ciNULLDEFAULTNULL,`msg`jsonNULL,PRIMARYKEY(`id`)USINGBTREE)ENGINE=InnoDBCHARACTERSET=utf8mb4COLLATE=utf8mb4_0900_ai......
  • python工具模块介绍-time 时间访问和转换
    快速入门In[1]:importtime#获取当前时间In[25]:time.strftime("%Y-%m-%d_%H-%M-%S",time.localtime())Out[25]:'2018-06-17_20-05-36'#停顿0.5秒In[26]:time.sleep(0.5)简介功能:时间访问和转换。相关模块:datetime 标准模块。calendar标准模块。下面介......
  • python jwt token使用
    官网https://pyjwt.readthedocs.io/en/latest/index.html#官网https://pyjwt.readthedocs.io/en/latest/index.html#我们在jwt.encode函数中使用了三个参数:#1)第一个是payload,主要用来存放有效的信息,例如用户名,过期时间等想要传递的信息。payload字典内部官方指定有指定ke......
  • python stata 交互
    pythonfromsfiimportDatafromsfiimportDatetimefromsfiimportFramefromsfiimportMacrofromsfiimportValueLabelcca="北京"ac=cca.split('')foriiinac:Macro.setLocal('x',ii)enddisp"`x'"py......
  • mysql求多列最大值
    1、使用列转行,每一列都转为一行数据,这样,直接比值就可以了。优点:比较常用,可以不用先求出每行或每列的最大值,转换后直接比值即可。缺点:大量使用union,union越多,性能越差,在数据量大的情况下不推荐。selectymd,max(value)from( selectname,oneasvaluefromt unionall s......
  • 详解Python当中的pip常用命令
    相信对于大多数熟悉Python的人来说,一定都听说并且使用过pip这个工具,但是对它的了解可能还不一定是非常的透彻,今天小编就来为大家介绍10个使用pip的小技巧,相信对大家以后管理和使用Python当中的标准库会有帮助。安装当然在Python3.4版本之后以及Python2.7.9版本之后,官网的安装......
  • python jupyter notebook使用
    安装:pipinstalljupyter 配置文件生成目录:jupyternotebook--generate-config ,生成默认配置文件到C:\Users\Administrator\.jupyter\jupyter_notebook_config.py运行:打开cmd命令提示符窗口输入jupyternotebook回车,然后浏览器就会打开Jupyternotebook。......
  • Excel控件开发调试
        基于VSTO开发Excel外接控件,VS调试Excel启动后不能出现开发后的控件,原因是在属性的调试选项里,添加Excel.exe: 针对listbox控件的几点使用代码:privatevoidbtn_RowToTop_Click(objectsender,EventArgse){intindex=this.listBoxRow.Se......
  • mysql查询上个季度数据
    mysql查询上季度数据个人博客地址:https://note.raokun.top拥抱ChatGPT,国内访问网站:https://www.playchat.top最近接口需要统计上个季度的数据统计,补一下sql季度函数:QUARTER(date)函数返回给定日期值(1到4之间的数字)的一年中的季度语法:QUARTER(date)参数描述......
  • MySQL查询某字段在哪些表中
    https://blog.csdn.net/qq_45722267/article/details/126350980?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3-126350980-blog-123066515.235%5Ev31%5Epc_relevant_default_base3&depth_1-utm_source......