文章内容

2017/9/19 17:26:52,作 者: 黄兵

Python实现CSV文件读取并保存到Microsoft Sql Server数据库

代码如下:

#coding=gbk
import csv
import re
import pyodbc
import datetime

def transformCodec(re_data): # ascii (gbk) 转 unicode
try:
re_data = re_data.decode('gbk')
except Exception as error:
print error
print 'delete illegal string,try again...'

pos = re.findall(r'decodebytesinposition([\d]+)-([\d]+):illegal', str(error).replace(' ', ''))
if len(pos) == 1:
re_data = re_data[0:int(pos[0][0])] + re_data[int(pos[0][1]):]
re_data = transformCodec(re_data)
return re_data
return re_data

def dataAddList(csvFile):
for row in csvFile:
rows.append(row)
rowNumber=len(rows)
return rowNumber

def store(title,context):
cursor.execute("INSERT INTO Articles (Title,CreateTime,Reader,ArticleBody,Category_Id,SEOId,AuthorId,Topic,ImgUrl,News,FirstProject,SecondProject) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
,title,datetime.datetime.now(),0,context,None,128,1,0,'http://fanti3.com:80/Images/UpLoadImages/2017918163336436.jpg',0,9,10)
cursor.connection.commit()

with open('sina_context.csv','rb') as csvfile:
spamreader = csv.reader(csvfile)
rows=[]
for item in range(1,dataAddList(spamreader)):
context=transformCodec(rows[item][1])
title=rows[item][0].decode('gbk')
conn = pyodbc.connect(r'DRIVER={SQL Server Native Client 10.0};SERVER=100.100.100.100,1555;DATABASE=00322485.com;UID=25875233;PWD=sdfwe8')
cursor = conn.cursor()
store(title,context)
print item

代码实现了CSV文件读取并保存到Microsoft Sql Server数据库的功能。

但是这个程序还不完善,有如下几点需要修改:

对于字符串的过滤,比如换行或者空行没有处理,读出来是什么样,保存到数据库就是什么样。

数据库没有关闭,对于资源是一个浪费。

对于错误的判断没有做需要完善。

中途遇到了很多问题,通过在网上寻找答案,最终把这个程序写出来了。

参考了很多资料,由于时间关系,我转载了互联网上的文章,有的没有写文章来源,在此表示歉意,如有侵权立删。

参考资料:

Python把对应格式的csv文件转换成字典类型存储脚本

python中的null值

Python转码问题的解决方法

AttributeError: 'list' object has no attribute 'decode'?

分享到:

发表评论

评论列表