为 MySQL 中现有列设置 NOT NULL 属性
要为现有列设置 NOT NULL 属性,请使用 ALTER TABLE 命令。我们先创建一个表 -
mysql> create table DemoTable1949 ( UserId int, UserName varchar(20) ); Query OK, 0 rows affected (0.00 sec)
这是一个为现有列设置 NOT NULL 属性的查询 -
mysql> alter table DemoTable1949 modify UserName varchar(20) not null; Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0
让我们查看表的描述 -
mysql> desc DemoTable1949;
这将产生以下输出 -
+----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | UserId | int(11) | YES | | NULL | | | UserName | varchar(20) | NO | | NULL | | +----------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1949 values(101,NULL); ERROR 1048 (23000): Column 'UserName' cannot be null mysql> insert into DemoTable1949 values(101,'Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1949 values(102,'Bob'); Query OK, 1 row affected (0.00 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1949;
这将产生以下输出 -
+--------+----------+ | UserId | UserName | +--------+----------+ | 101 | Chris | | 102 | Bob | +--------+----------+ 2 rows in set (0.00 sec)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP