最近看了廖雪峰老师的Mysql视频,简单做个记录
基本语句
mysql -u root -p //进入数据库
show databases; // 查看所有数据库
create database 数据库名; //新建数据库
drop database 数据库名; //删除数据库
use 数据库名; //选择数据库
show tables; //展示数据库中的数据表
create table 表名(
......
); //创建数据库中的数据表
创建表的示例:
create table 表名(
id int not null auto_increment, //不为空,并且自增
name varchar(10) not null, //不为空
primary key(id)
);
insert语句
insert into 表名 (字段1,字段2...) values (数据1,数据2...);
insert into 表名 (字段2...) values (数据2...); //如果字段1是自增字段
insert into 表名 values (数据1,数据2...); //如果能保证字段和数据顺序一致
select语句
//返回一个二维表
select * from 表名; //返回整个二维表
select * from 表名 where aa=x; //返回满足要求的指定的行
select * from 表名 where aa=x and bb=y; // 返回满足多个要求的指定的行
select aa,bb from 表名; //返回指定的列
select count(*) from 表名; //返回表里面的数据条数,这个二维表(1*1)以count(*)命名
select count(*) number from 表名; //返回表里面的数据条数,这个二维表以number命名
select count(*) number from 表名 group by aa; //返回表里面的数据条数,这个变量以number命名,并且以aa为尺度将这个变量划分为若干条
select aa,count(*) number from 表名 group by aa; //只能是aa,不能是其他表项
select * from 表名1,表名2; //如果表1有m条记录,表2有n条记录,表1和表2有对应关联键,那么返回表有m*n条记录
select * from 表名1,表名2 inner join + 条件;
update语句
//返回的值是int值,是符合条件的更新的记录数目
update 表名 set aa=x; //更新某些项目的数值
update 表名 set aa=x where bb=y; //筛选符合条件的行
update 表名 set aa=x,cc=z where bb=y; //更新多个数值
delete语句
delete from 表名; //删除整个表
delete from 表名 where aa=x; //删除指定的行
delete from 表名 where aa=x and bb=y; //删除有更多限制的指定的行
JDBC查询
代码太多,先放一张图吧
几点说明:
- Connection: 获取数据库驱动的连接对象
- PreparedStatement :从连接中获取sql表达式,?表示占位符,规避sql注入漏洞
- setObject: 将指定处的占位符替换成具体数据,索引从1开始
- executeQuery: 将表达式执行查询,返回一个结果集合
- next: 遍历每一条记录,进行处理
JDBC更新
各代码功能与JDBC查询相似
其中,更新的结果是int