zoukankan      html  css  js  c++  java
  • mysql数据库和数据表的简单操作

    一.数据库的增删改查

    1.新建数据库

    CREATE DATABASE 数据库名 charset utf8;

    数据库名规则:可以由字母、数字、下划线、@、#、$ 区分大小写, 不能使用关键字如 create select, 不能单独使用数字, 最长128位

    2.查看数据库

    show databases;
    show create database 数据库名;

    3.选择数据库

    USE 数据库名;

    4.删除数据库

    DROP DATABASE 数据库名;

    5.修改数据库字符编码

    alter database 数据库名 charset utf8;

    二.数据表的增删改查

    1.创建表

    create table 表名(字段名1 类型[(宽度) 约束条件],字段名2 类型[(宽度) 约束条件],......);

    注意:同一张表中字段名不能相同,字段名和类型必选,宽度和约束条件可选

    create table test(id int, name varchar(50),age int(3),sex enum('male','female'));

    表中插入数据

    insert into test values(1,'tom',18,'male'),(2,'jerry',15,'female');

    2.查看表结构

    describe test;
    show create table testG; #查看表详细结构,可加G显示

    3.修改表结构

    a.修改表名

    ALTER TABLE 表名 RENAME 新表名;

    b.增加表字段

    ALTER TABLE 表名 ADD 字段名  数据类型 [完整性约束条件…],ADD 字段名  数据类型 [完整性约束条件…]; #添加一个或多个字段
    ALTER TABLE 表名 ADD 字段名  数据类型 [完整性约束条件…]  FIRST; #在最前面增加字段
    ALTER TABLE 表名 ADD 字段名  数据类型 [完整性约束条件…]  AFTER 字段名; #在某个字段后增加字段
    alter table student add name varchar(20) not null,add age int(3) not null default 22;
    alter table student add stu_num varchar(10) not null after name; 
    alter table student add sex enum('male','female') default 'male' first; 

    c.删除字段

    ALTER TABLE 表名 DROP 字段名;
    alter table student drop sex;

    d.修改字段

    ALTER TABLE 表名  MODIFY  字段名 数据类型 [完整性约束条件…];
    ALTER TABLE 表名 CHANGE 旧字段名 新字段名 旧数据类型 [完整性约束条件…];
    ALTER TABLE 表名 CHANGE 旧字段名 新字段名 新数据类型 [完整性约束条件…];
    alter table student modify id int(11) not null primary key auto_increment; #修改id字段类型非空主键自动增长
    alter table student modify id int(11) not null; #删除自动增长
    alter table student drop primary key; #删除主键

    4.复制表

    复制表结构+记录 (不会复制: 主键、外键和索引)

    create table new_service select * from service;

    只复制表结构

    create table new1_service select * from service where 1=2; #设置条件为假使数据查不到只有结构

    5.删除表

    DROP TABLE 表名;
  • 相关阅读:
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    微信小程序TodoList
    C语言88案例-找出数列中的最大值和最小值
    C语言88案例-使用指针的指针输出字符串
  • 原文地址:https://www.cnblogs.com/fanhk/p/9279911.html
Copyright © 2011-2022 走看看