连接数据库时的编码问题
报错
python编码错误:UnicodeDecodeError: 'utf8' codec can't decode
或者UnicodeDecodeError: 'ascii' codec can't decode byte 0xcf in position 7: ordinal not in range(128)
考虑使用如下方法http://www.jb51.net/article/59297.htm
代码如下
#coding:utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') import mysql.connector cnx =mysql.connector.connect(user='bitbear',password='bittest123',host='101.201.50.1',database='bitbear',charset='utf8')
参考https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001391435131816c6a377e100ec4d43b3fc9145f3bb8056000
#coding:utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') import mysql.connector conn =mysql.connector.connect(user='bitbear',password='bittest123',host='101.201.50.1',database='bitbear',charset='utf8') cursor = conn.cursor() cursor.execute('create table usertest (id varchar(20) primary key, name varchar(20))') cursor.execute('insert into usertest (id, name) values (%s, %s)', ['1', 'Michael']) cursor.rowcount conn.commit() cursor.close()
参考:http://www.cnblogs.com/bigberg/p/6430095.html
数据库汇总usertest1.py中id字段为自增的情况下,向其中插入json
#coding:utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') import mysql.connector import json test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]} print(test_dict) print(type(test_dict)) json_str = json.dumps(test_dict) print(json_str) print(type(json_str)) ##### conn =mysql.connector.connect(user='bitbear',password='bittest123',host='101.201.50.1',database='bitbear',charset='utf8') cursor = conn.cursor() #cursor.execute('create table usertest (id varchar(20) primary key, name varchar(20))') cursor.execute('insert into usertest1 ( name) values ( %s)', [ json_str]) cursor.rowcount conn.commit() cursor.close()
使用本地文件读取,参考:http://blog.csdn.net/dyx404514/article/details/50186413
将json数据存储在my.json中,打开后存到变量x中,格式为字符串,然后可以直接写到数据库中,代码如下
#coding:utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') import mysql.connector import json as js #f = file('./my.json') #x=js.loads(f) #print x with open('./my.json', 'r') as f: x=f.read() print type(x) ##### conn =mysql.connector.connect(user='bitbear',password='bittest123',host='101.201.50.1',database='bitbear',charset='utf8') cursor = conn.cursor() #cursor.execute('create table usertest (id varchar(20) primary key, name varchar(20))') cursor.execute('insert into usertest1 ( name) values ( %s)', [x]) cursor.rowcount conn.commit() cursor.close()
使用pycharm2017+python3.6连接数据库时无法导入mysql以及mysqldb
mysqldb暂不支持python3.6,使用pymysql
参考:https://www.cnblogs.com/hank-chen/p/6624299.html
pycharm激活
http://blog.csdn.net/mr_hhh/article/details/79062747