python -mysqldb 查询和插入问题

1.系统环境:
python 2.7

2.在使用MySQLdb模块的时候发现:
db=MySQLdb.connect(host=“localhost”,user=“root”,passwd=“123456”,db=“student”,charset="utf8")
cursor=db.cursor()
sql="select * from student"
cursor.execute(sql)
results=cursor.fetchmany(5)
fi=open("/tmp/python-save",'wb')
for i in results:

Str=i.__str__()
fi.write(Str)

fi.close()

但是在获取的内容中出现
(946936L, 1333L, u'G-001-001B', u'622909326808922712', u'*xe7u0178xb3xe6u02dcu017dxe6xb5xb7', 141301594L, 0.0, 4800.0, u'020000009669', Decimal('1.00'), 1, 0.0, 0.0, 0.0, 0.0, 100.0, datetime.datetime(2016, 6, 20, 14, 41, 41), datetime.datetime(2016, 6, 21, 10, 13, 4), 2762L, 0L, 0L, None, 1613258L, datetime.date(2016, 7, 3), 1)

有两个问题:

1.获取内容中的u'*xe7u0178xb3xe6u02dcu017dxe6xb5xb7' 为什么不显示中文,已经尝试了很多次,将编码该加的都加了,(encoding,python环境,数据库编码),有什么办法可以解决的吗?

2.想将上面的一条语句再次插入到原表中(在插入之前,原表中的原数据已经被删除,不会出现主键报错,不让插入该语句的情况)
直接插入上面的语句肯定是不行的(数据中存在字段的类型),有什么办法将上面的语句转换成可以直接插入的语句吗。(不要一个一个的赋值)

谢谢!

results:
((946936L, 1333L, u'G-001-001B', u'622909326808922712', u'xe7u0178xb3xe6u02dcu017dxe6xb5xb7', 141301594L, 0.0, 4800.0, u'020000009669', Decimal('1.00'), 1, 0.0, 0.0, 0.0, 0.0, 100.0, datetime.datetime(2016, 6, 20, 14, 41, 41), datetime.datetime(2016, 6, 21, 10, 13, 4), 2762L, 0L, 0L, None, 1613258L, datetime.date(2016, 7, 3), 1), (946938L, 1155L, u'G-001-005', u'966666323355759717', u'xe5xbcxa0xe5xadxa6', 132001643L, 0.38, 2880.0, u'020000020580', Decimal('1.00'), 1, 0.0, 0.0, 0.0, 0.0, 99.62, datetime.datetime(2016, 6, 20, 15, 25, 38), datetime.datetime(2016, 6, 21, 10, 13, 5), 2762L, 20212L, 2L, None, 1613272L, datetime.date(2016, 7, 13), 1), (946940L, 1134L, u'J-002-012', u'966666323504681316', u'xe6x9du017dxe6u02dcxa5xe5x8du017d', 131300758L, 12.16, 6187.0, u'020000020582', Decimal('1.00'), 1, 0.0, 0.0, 0.0, 0.0, 3187.84, datetime.datetime(2016, 6, 20, 15, 35, 26), datetime.datetime(2016, 6, 21, 10, 13, 5), 2762L, 19937L, 2L, None, 1613276L, datetime.date(2016, 7, 13), 1), (946942L, 1151L, u'S-002-003', u'622909326232874711', u'xe5xadu2122xe6xb5xb7xe6xbax90', 131600574L, 11.32, 3278.0, u'020000020583', Decimal('1.00'), 1, 0.0, 0.0, 0.0, 0.0, 2968.68, datetime.datetime(2016, 6, 20, 15, 38, 26), datetime.datetime(2016, 6, 21, 10, 13, 5), 2762L, 20036L, 2L, None, 1613278L, datetime.date(2016, 6, 26), 1), (946946L, 1353L, u'G-001-001', u'966666323782153913', u'*xe5x8fxb6xe5u0153xa3xe6u2030x8d', 141801664L, 0.0, 7360.0, u'020000020587', Decimal('1.00'), 1, 0.0, 0.0, 0.0, 0.0, 100.0, datetime.datetime(2016, 6, 20, 16, 28, 24), datetime.datetime(2016, 6, 21, 10, 13, 5), 2762L, 0L, 0L, None, 1613290L, datetime.date(2016, 7, 2), 1))

阅读 1.9k
1 个回答

贴一下print results的输出结果。ps: 写入文件的时候没必要"wb"吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题