编辑:
- 根据用户的 cmets,向此测试添加了失败地址。此地址加载到数据库没有问题。
- 添加了将 CSV 地址存储到 MySQL 中的代码。
答案:
以下代码执行以下操作:
- MySQL 数据库
engine(连接)已创建。
- 从 CSV 文件中读取的地址数据(编号、地址)。
- 从源数据中替换了非字段分隔逗号,并删除了多余的空格。
- 编辑后的数据输入
DataFrame
-
DataFrame 用于将数据存储到 MySQL 中。
import csv
import pandas as pd
from sqlalchemy import create_engine
# Set database credentials.
creds = {'usr': 'admin',
'pwd': '1tsaSecr3t',
'hst': '127.0.0.1',
'prt': 3306,
'dbn': 'playground'}
# MySQL conection string.
connstr = 'mysql+mysqlconnector://{usr}:{pwd}@{hst}:{prt}/{dbn}'
# Create sqlalchemy engine for MySQL connection.
engine = create_engine(connstr.format(**creds))
# Read addresses from mCSV file.
text = list(csv.reader(open('comma_test.csv'), skipinitialspace=True))
# Replace all commas which are not used as field separators.
# Remove additional whitespace.
for idx, row in enumerate(text):
text[idx] = [i.strip().replace(',', '') for i in row]
# Store data into a DataFrame.
df = pd.DataFrame(data=text, columns=['number', 'address'])
# Write DataFrame to MySQL using the engine (connection) created above.
df.to_sql(name='commatest', con=engine, if_exists='append', index=False)
源文件(comma_test.csv):
"12345" , "123 abc street, Unit 345"
"10101" , "111 abc street, Unit 111"
"20202" , "222 abc street, Unit 222"
"30303" , "333 abc street, Unit 333"
"40404" , "444 abc street, Unit 444"
"50505" , "abc DR, UNIT# 123 UNIT 123"
未经编辑的数据:
['12345 ', '123 abc street, Unit 345']
['10101 ', '111 abc street, Unit 111']
['20202 ', '222 abc street, Unit 222']
['30303 ', '333 abc street, Unit 333']
['40404 ', '444 abc street, Unit 444']
['50505 ', 'abc DR, UNIT# 123 UNIT 123']
编辑数据:
['12345', '123 abc street Unit 345']
['10101', '111 abc street Unit 111']
['20202', '222 abc street Unit 222']
['30303', '333 abc street Unit 333']
['40404', '444 abc street Unit 444']
['50505', 'abc DR UNIT# 123 UNIT 123']
从 MySQL 查询:
number address
12345 123 abc street Unit 345
10101 111 abc street Unit 111
20202 222 abc street Unit 222
30303 333 abc street Unit 333
40404 444 abc street Unit 444
50505 abc DR UNIT# 123 UNIT 123
致谢:
这是一个冗长的方法。但是,为了清楚地显示所涉及的步骤,我们特意对每个步骤进行了细分。