python连接mysql并让mysql支持中文

来源:互联网 发布:name域名续费优惠码 编辑:程序博客网 时间:2024/05/17 18:14

ubuntu下安装mysql

sudo apt-get install mysql-serversudo apt-get install mysql-client

  在安装过程中会提示确认输入YES,设置 root 用户密码(之后也可以修改)等,稍等片刻便可安装成功。

  之后可以使用如下命令打开mysql:

sudo service mysql startmysql -u root -p    #如果没有密码不需要输入 -p

python连接mysql

  首先安装MySQLdb,MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。

sudo apt-get install python-mysqldb  #python2sudo apt-get install python3-mysqldb  #python3

  尝试导入MySQLdb模块检测是否安装成功

import MySQLdb

  接下来开始连接操作数据库

import MySQLdb# 打开数据库连接。db = MySQLdb.connect("localhost","user","password","db_name" )# 使用cursor()方法获取操作游标 cursor = db.cursor()#执行sql语句#创建数据表#cursor.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")#插入一条数据#cursor.execute("insert into student values('2','Tom','3 year 2 class','9')")#一次插入多条记录#executemany()方法可以一次插入多条值,执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数。sqlExp = "insert into student values(%s,%s,%s,%s)"cursor.executemany(sqlExp,[    ('3','Tom','1 year 1 class','6'),    ('3','Jack','2 year 1 class','7'),    ('3','Yaheng','2 year 2 class','7'),    ])#获得表中的多条数据并打印出来#获得表中有多少条数据aa = cursor.execute("select * from student")#打印表中的多少数据info = cursor.fetchmany(aa)    #获得多条数据for i in info:    print(i)#修改查询条件的数据#cursor.execute("update student set class='3 year 1 class' where name = 'Tom'")#删除查询条件的数据#cursor.execute("delete from student where age='9'")#关闭数据库游标cursor.close()#提交事务。没有这一步数据库内容不会改变db.commit()#关闭数据库连接db.close()

  mysql默认的编码方式不支持中文。如何使mysql支持中文?

  1、在每次创建表的时候都在最后加上

     character set = utf8

  就可以很好的支持中文。

create table entries2 (       id     int auto_increment,        title  text,       content  text,       posted_on  datetime,       primary key (id)   ) character set = utf8;

  2、修改已经有的table的编码,当使用默认编码创建了一个table的时候,是不能支持中文的,这时候使用如下语句对table_name进行修改:

alter table table_name convert to character set utf8;

  python在连接mysql的时候也要设置编码格式:

# 打开数据库连接。db = MySQLdb.connect("localhost","user","password","db_name, charset='utf8'" ) 
原创粉丝点击