mysql数据库操作

环境

系统:ubuntu18.04
版本:mysql 5.7.25

  1. 安装
    参考:https://blog.csdn.net/v6543210/article/details/100314986

安装库文件:
apt install libmysqlclient-dev


基本步骤就是:

使用mysql_init()初始化连接
使用mysql_real_connect()建立一个到mysql数据库的连接
使用mysql_query()执行查询语句
result = mysql_store_result(mysql)获取结果集
mysql_num_fields(result)获取查询的列数,mysql_num_rows(result)获取结果集的行数
通过mysql_fetch_row(result)不断获取下一行,然后循环输出
释放结果集所占内存mysql_free_result(result)
mysql_close(conn)关闭连接

################## 数据库mysql基本操作命令###################

  1. 创建一个数据库
    CREATE DATABASE zw_db;

  2. 创建用户表
    user zw_db;

CREATE TABLE t_user(uid int(10) PRIMARY KEY, username varchar(20) NOT NULL, password varchar(20) NOT NULL, token varchar(50));

INSERT INTO t_user (uid, username, password) values (100, “n1”, “zw1”);

  1. 设置唯一属性

alter table tb_name add unique key unique_category_type (字段名);
alter table t_auth_device add unique key unique_category_type (sign)

删除唯一约束
ALTER TABLE tb_name DROP {INDEX | KEY} index_name;

  1. 删除表数据
    delete from 表名,删除表数据, 仍然认可记录

    truncate table 表名,直接清空表,相当于重建表
    drop table 表名,删除表

  2. 更改
    4.1 字段类型
    alter table 表名 modify column 字段名 类型;

    alter table t_auth_device modify column at_name varchar(20);

  3. 新增字段
    1、指定列之后:
    ALTER TABLE foo ADD id INT(4) AFTER column_i;
    ALTER TABLE t_allocation_record ADD ac_id INT(4) AFTER username;

auto t_pSn = pSession.lock();
const std::string user_name = t_pSn->get_datastd::string(“user_name”);
const std::string ac_id = t_pSn->get_datastd::string(“ac_id”);

示例

  1. 创建名字为oneDataBase的数据库
CREATE DATABASE IF NOT EXISTS oneDataBase;
  1. 创建表
    先设计一个表如下:
学生学号学生姓名课程名成绩
0601张三语文85
0602李四数学63
0601张三数学95
0602李四语文83
0603王五语文85
0603王五数学63

生成表,表名为score:

// 先选择数据库,然后才能操作表
use oneDataBase; 

// 创建表
##create table score if not exit (学生学号 VARCHAR(20), 学生姓名VARCHAR(20), 课程名 VARCHAR(20), 成绩 int);
//没有设置支持中文,这里先用英文代替
create table score(sid VARCHAR(20), name VARCHAR(20),course VARCHAR(20),score int)character set = utf8;

// 插入数据
insert into score  values('0601' ,'张三' ,' 语文' , 85);
insert into score  values('0602' ,'李四' ,' 数学' , 63);
insert into score  values('0601' ,'张三' ,' 数学' , 95);
insert into score  values('0602' ,'李四' ,' 语文' , 83);
insert into score  values('0603' ,'王五' ,' 语文',  85);
insert into score  values('0603' ,'王五' ,' 数学',  63);

// 觉得表名不好,修改表名为studentScore
alter table score rename studentScore;
  1. 查询语句
    查询所有成绩均大于80的学生的sid, name
select distinct sid, name from studentScore 
where score > 80 
and 
sid not in (select sid from studentScore where score < 80);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值