mysql之CREATE DATABASE Syntax(创建数据库)

一:语法

CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name       #SCHEMA是DATABASE的同义词  [IF NOT EXITTS]可防止建库是已经存在报错
    [create_specification] ...                           #可指定数据库的特征

create_specification:
    [DEFAULT] CHARACTER SET [=] charset_name             #指定字符集
  | [DEFAULT] COLLATE [=] collation_name                 #specifies the default database collation (排序规则)
例如:创建数据库并指定字符集
  create database db2 default character set=utf8

备注:数据库的字符集存储在数据库目录下的db.opt文件中,我们可通过  find / -name db.opt  查找并用less 查看相关db.opt文件如下

     

二:关于  CHARACTER SET  和   COLLATE 

三:查看相关字符集

3.1 :查看MYSQL数据库服务器和数据库字符集   

方法一:show variables like '%character%';
方法二:show variables like 'collation%';

3.2 :查看表的字符集(show table status from 库名 like  表名)

show table status from test3 like 'students';

3.4 :查看表中所有列的字符集(show full columns from 表名;)

show full columns from test3.students;

注意:数值型的列没有 collation特性

四:修改相关的字符集

4.1.创建时指定字符集

建库时指定
create database db2 default character set=utf8
建表时指定
create table test1(id int(6),name char(10)) default character set = 'gbk';

4.2修改相关字符集

扫描二维码关注公众号,回复: 5144703 查看本文章
修改全局字符集
/*建立连接使用的编码*/
set character_set_connection=utf8;
/*数据库的编码*/
set character_set_database=utf8;
/*结果集的编码*/
set character_set_results=utf8;
/*数据库服务器的编码*/
set character_set_server=utf8;

set character_set_system=utf8;

set collation_connection=utf8;

set collation_database=utf8;

set collation_server=utf8;

4.3 修改库的字符集(alter database 库名 default character set 字符集;)

mysql> show create database shiyan\G
*************************** 1. row ***************************
       Database: shiyan
Create Database: CREATE DATABASE `shiyan` /*!40100 DEFAULT CHARACTER SET utf8 */
1 row in set (0.00 sec)

mysql> alter database shiyan default character set gbk;
Query OK, 1 row affected (0.00 sec)

4.4修改表字符集(alter table 表名 convert to character set 字符集;)

修改表的字符集
mysql> show create table test1\G
*************************** 1. row ***************************
       Table: test1
Create Table: CREATE TABLE `test1` (
  `id` int(6) DEFAULT NULL,
  `name` char(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=gbk   #原字符集
1 row in set (0.00 sec)

mysql> alter table test1 convert to character set utf8;
Query OK, 0 rows affected (0.58 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table test1\G
*************************** 1. row ***************************
       Table: test1
Create Table: CREATE TABLE `test1` (
  `id` int(6) DEFAULT NULL,
  `name` char(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8   #修改后的字符集
1 row in set (0.00 sec)

 4.5修改字段的字符集(alter table 表名 modify 字段名 字段属性 character set gbk;)

alter table test1 modify name char(10) character set gbk;

五:案例分析

  当我们不知道因和原因创建的一个表(teacher),当我们向表中插入数据是发生乱码如下

  sql : INSERT INTO teacher(tid,class_id,NAME)VALUE(312,2,'小明');

  

  

猜你喜欢

转载自www.cnblogs.com/jinliang374003909/p/10349884.html