对mysql 数据库操作 使其支持插入中文(针对python)

首先,这项任务确切的说需要三步吧:

#1.建立数据库(数据库名为xsk)

create database `xsk` character set 'utf8' collate 'utf8_general_ci';

#2.建表:

#!/usr/bin/python

#ecoding=utf-8
import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

#这里表示连接数据库(localhost,testuser,testpassword,test,encode)

db=MySQLdb.connect('localhost','root','密码','xsk',charset='utf8')
cursor=db.cursor()

sql="""create table user(id varchar(20) not null default '',
                                     name varchar(20) not null default ''
                                     )ENGINE=InnoDB DEFAULT CHARSET=utf8;"""

cursor.execute(sql)

db.close()

#怎么插入数据就不说了,插入之后的表:

+----+-----+
| id | name |
+---+-----+
| 1 | 刘备 |
| 2 | 张飞 |
| 3 | 关羽 |
| 4 | 赵云 |
+----+-----+

#3.其实第三步就是,这在第二步里面已经有了,不过是强调一下(这只在python2中能用,python3是不支持的)

#一定要在代码中加入这些:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

#4.然后你就可以运行你的代码了

 1 #!/usr/bin/python
 2 #ecoding=utf-8
 3 import MySQLdb
 4 import sys
 5 reload(sys)
 6 sys.setdefaultencoding('utf-8')
 7 
 8 db=MySQLdb.connect('localhost','root','1','xsk',charset='utf8')
 9 cursor=db.cursor()
10 sql="select *from user"
11 try:
12         cursor.execute(sql)
13         results=cursor.fetchall()
14         for row in results:
15                 print("%s %s" % (row[0],row[1]))
16 except Exception as e:
17         print("%s",str(e))
18 db.close()

#运行结果:

1  刘备

2  张飞

3  关羽

4  赵云

原文地址:https://www.cnblogs.com/nyist-xsk/p/7264778.html