汇总一下,自己最近在使用Python读写CSV存数据库中遇到的各种问题。
相关mysql视频教程推荐:《mysql教程》
上代码:
reload(sys) sys.setdefaultencoding('utf-8') host = '127.0.0.1' port = 3306 db = 'world' user = 'root' password = '123456' con = MySQLdb.connect(host=host,charset="utf8",port=port,db=db,user=user,passwd=password) try: df = pd.read_sql(sql=r'select * from city', con=con) df.to_sql('test',con=con,flavor='mysql') except Exception as e: print(e.message)
不出意外的话会打印出一句:database flavor MySQL is not supported
在stackoverflow上找到了答案:The flavor ‘mysql’ is deprecated in pandas version 0.19.
我们换一种方式:
reload(sys) sys.setdefaultencoding('utf-8') host = '127.0.0.1' port = 3306 db = 'world' user = 'root' password = '123456' engine = create_engine(str(r"mysql+mysqldb://%s:" + '%s' + "@%s/%s") % (user, password, host, db)) try: df = pd.read_sql(sql=r'select * from city', con=engine) df.to_sql('test',con=engine,if_exists='append',index=False) except Exception as e: print(e.message)
运行下,ok,可以存入了index参数表示是否把DataFrame的index当成一列来存储,一般来说是不需要的,所以赋值为False
现在看似问题都解决了,但是还有一个小问题。
假如我有一个含有中文的csv文件(本人Window):
name age class
小明 15 一年级
小张 18 三年级
engine = create_engine(str(r"mysql+mysqldb://%s:" + '%s' + "@%s/%s") % (user, password, host, db)) try: df = pd.read_csv(r'C:\Users\xx\Desktop\data.csv') print(df) df.to_sql('test', con=engine, if_exists='append', index=False) except Exception as e: print(e.message)
打印处理以后乱码了。我们在读csv时候最好指定编码,我的本地GBK:
df = pd.read_csv(r'C:\Users\xx\Desktop\data.csv',encoding='gbk')
我们可以正常的打印信息了,但是又报错了,错误如下:
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)
还是编码问题,原因呢,我们存到数据库时候没有指定编码。解决这个问题时候也是被坑了一把,网上说什么的都有。过程就不说了,看代码:
engine = create_engine(str(r"mysql+mysqldb://%s:" + '%s' + "@%s/%s?charset=utf8") % (user, password, host, db))
解决了
相关文章:
用Python的pandas框架操作Excel文件中的数据教程
以上是Python用Pandas读CSV文件写到MySQL的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表sandnumpyArraysInpyThonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,withoverHeadeBheadaroundAroundaroundaround64bytaround64bitson64-bitsysysysyssyssyssyssyssyssysssys2)

toensurepythonscriptsbehavecorrectlyacrycrossdevelvermations,登台和生产,USETHESTERTATE:1)Environment varriablesforsimplesettings,2)configurationFilesForefilesForcomPlexSetups,3)dynamiCofforAdaptapity.eachmethodofferSuniquebeneiquebeneiquebeneniqueBenefitsaniqueBenefitsandrefitsandRequiresandRequireSandRequireSca

Python列表切片的基本语法是list[start:stop:step]。1.start是包含的第一个元素索引,2.stop是排除的第一个元素索引,3.step决定元素之间的步长。切片不仅用于提取数据,还可以修改和反转列表。

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/删除,2)储存的二聚体和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,请考虑performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

记事本++7.3.1
好用且免费的代码编辑器

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Dreamweaver CS6
视觉化网页开发工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。