Java学习-Day07-MySQL与JDBC编程(1)

2018-03-29  本文已影响0人  Indomi

1.JDBC基础

JDBC:Java DataBase Connectivity即Java数据库连接,一种可以执行SQL语句的Java API

可以完成
1.建立与数据库连接
2.执行SQL语句
3.获得SQL语句的执行结果

2.MySQL

2.1存储机制

3.SQL语句

结构化查询语言,用于操作任何关系数据库,不区分大小写

标准SQL语句分为:

3.1 DDL语句
常见数据库对象
3.1.1 创建表
create table [模式名.]表名(
  #可以有多个列定义
  test_id int,
  test_price decimal,
  #给默认值
  test_name varchar(255) default 'xxx',
  #大文本类型
  test_desc text,
  #图片
  test_img blob,
  test_date datetime
)
MySQL支持的列类型
create table hehe
as
select * user_inf;
#建立一个表hehe和user_inf表完全相同,数据也相同
3.1.2 修改表结构
#增加一个字段
alter table hehe
add hehe_id int;
#增加两个字段
alterr table hehe
add(
  aaa varchar(255) default 'xxx',
  bbb varchar(255)
);
#修改字段类型 每次只能修改一个列定义
alter table hehe
modify hehe_id varchar(255);
#删除字段
alter table hehe
drop aaa;
#重命名数据表
alter table 表名
rename to 新表名;
#重命名字段名.bbb改为aaa,数据类型为int
alter table hehe 
change bbb aaa int;
3.1.3 删除表
#删除
drop table hehe;
3.1.4 truncate表
3.2 数据库约束
3.2.1 NOT NULL约束
3.2.2 UNIQUE约束
create tabnle unique_test(
  test_name varchar(255),
  test_pass varchar(255),
  #使用表级约束语法建立唯一约束,指定两列组合不允许重复
  #test2_uk要求两个字段都不能出现重复值
  unique (test_name),
 constraint test2_uk unique(test_pass),
  #test3_uk要求两列值得组合不能重复
  constraint test3_uk unique(test_name,test_pass)
);

也可以在修改表结构时使用add关键字

alter table unique_test
add unique(test_name,test_pass);
3.2.3 PRIMARY KEY约束
3.2.4FOREIGN KEY约束
create table teacher_table(
  # auto_increment 代表数据库的自动编号策略,通常用作数据表的逻辑主键
  teacher_id int auto_increment,
  teacher_name varchar(255),
  primary key(teacher_id)
);
create table student_table(
  student_id int auto_increment primary key,
  student_name varchar(255),
  #指定java_teacher参照到teacher_table的teacher_id列
  java_teacher int references teacher_table(teacher_id)
);
上一篇 下一篇

猜你喜欢

热点阅读