Fork me on GitHub

MySQL50-2-解决字符集问题

MySQL经典50题-2-解决字符集问题

在创建完数据库和表之后,需要插入模拟数据。在插入的过程中就碰到了问题,此文作为记录解决字符集的问题

  • 修改MySQL字符集
  • 查看库、表、字段的字符集
  • 指定表、字段的字符集

创建表

  1. 学生表
1
2
3
4
5
6
7
mysql> create table Student(
-> s_id varchar(20),
-> s_name varchar(20) not null default '',
-> s_birth varchar(20) not null default '',
-> s_sex varchar(20) not null default '',
-> primary key(s_id));
Query OK, 0 rows affected (0.02 sec)

  1. 课程表
1
2
3
4
5
6
mysql> create table Course(
-> c_id varchar(20),
-> c_name varchar(20) not null default '',
-> t_id varchar(20) not null,
-> primary key(c_id));
Query OK, 0 rows affected (0.01 sec)

  1. 教师表
1
2
3
4
5
mysql> create table Teacher(
-> t_id varchar(20),
-> t_name varchar(20) not null default '',
-> primary key(t_id));
Query OK, 0 rows affected (0.01 sec)

  1. 成绩表
1
2
3
4
5
6
mysql> create table Score(
-> s_id varchar(20),
-> c_id varchar(20),
-> s_score int(3),
-> primary key(s_id,c_id));
Query OK, 0 rows affected (0.00 sec)

报错解决

报错原因

在创建了表之后直接往Student表中插入数据,报错了:

网上找到了原因:库、表和字段的字符集不同造成的

解决方案

如何查看数据集

查看mysql的字符集:

1
show variables where Variable_name like '%char%';

查看某一个数据库字符集:

1
show create database test;

查看某一个数据表字符集:

1
show create table Student;

具体解决步骤:

  1. 修改数据库和表的字符集

  1. 指定字段的字符集

  1. 字符集相同

最终成功插入数据:

修改MySQL字符集

1
2
3
4
5
6
7
mysql> set character_set_client=utf8;
mysql> set character_set_connection=utf8;
mysql> set character_set_database=utf8;
mysql> set character_set_results=utf8;
mysql> set character_set_server=utf8;
mysql> set character_set_system=utf8;
mysql> set collation_connection=utf8;

本文标题:MySQL50-2-解决字符集问题

发布时间:2020年10月29日 - 23:10

原始链接:http://www.renpeter.cn/2020/10/29/MySQL50-2-%E8%A7%A3%E5%86%B3%E5%AD%97%E7%AC%A6%E9%9B%86%E9%97%AE%E9%A2%98.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea