【Java】-NO.16.EBook.4.Java.1.012-【疯狂Java讲义第3版 李刚】- JDBC

1.0.0 Summary

Tittle:【Java】-NO.16.EBook.4.Java.1.012-【疯狂Java讲义第3版 李刚】-  JDBC

Style:EBook

Series:Java

Since:2017-10-08

End:....

Total Hours:...

Degree Of Diffculty:2

Degree Of Mastery:2

Practical Level:2

Desired Goal:2

Archieve Goal:....

Gerneral Evaluation:...

Writer:kingdelee

Related Links:

http://www.cnblogs.com/kingdelee/

1.

【Java】-NO.16.EBook.4.Java.1.012-【疯狂Java讲义第3版 李刚】-  JDBC

2.SQL type:

2.1 Query

select ....

2.2 DML(Data Manipulation Language,数据操作语言)

insert, update, delete

2.3 DDL (Data Definition Language,数据定义语言)

create, alter, drop, truncate

2.4 DCL (Data Control Language,数据控制语言)

grant, revoke

2.5 Transaction

commit, rollback, savepoint

3. DDL

【Java】-NO.16.EBook.4.Java.1.012-【疯狂Java讲义第3版 李刚】-  JDBC

3.1 create 创建表

create table [模式名.]表名 (
列名 类型 [默认表达式]
) create table tb_test (
test_id int,
name varchar(255) default 'xxx' )

detail:https://dev.mysql.com/doc/refman/5.7/en/create-table.html

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options] CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
[partition_options]
[IGNORE | REPLACE]
[AS] query_expression CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
{ LIKE old_tbl_name | (LIKE old_tbl_name) } create_definition:
col_name column_definition
| [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...)
[index_option] ...
| {INDEX|KEY} [index_name] [index_type] (index_col_name,...)
[index_option] ...
| [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY]
[index_name] [index_type] (index_col_name,...)
[index_option] ...
| {FULLTEXT|SPATIAL} [INDEX|KEY] [index_name] (index_col_name,...)
[index_option] ...
| [CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name,...) reference_definition
| CHECK (expr) column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
[COMMENT 'string']
[COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]
[STORAGE {DISK|MEMORY|DEFAULT}]
[reference_definition]
| data_type [GENERATED ALWAYS] AS (expression)
[VIRTUAL | STORED] [UNIQUE [KEY]] [COMMENT comment]
[NOT NULL | NULL] [[PRIMARY] KEY] data_type:
BIT[(length)]
| TINYINT[(length)] [UNSIGNED] [ZEROFILL]
| SMALLINT[(length)] [UNSIGNED] [ZEROFILL]
| MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]
| INT[(length)] [UNSIGNED] [ZEROFILL]
| INTEGER[(length)] [UNSIGNED] [ZEROFILL]
| BIGINT[(length)] [UNSIGNED] [ZEROFILL]
| REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]
| DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]
| FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]
| DECIMAL[(length[,decimals])] [UNSIGNED] [ZEROFILL]
| NUMERIC[(length[,decimals])] [UNSIGNED] [ZEROFILL]
| DATE
| TIME[(fsp)]
| TIMESTAMP[(fsp)]
| DATETIME[(fsp)]
| YEAR
| CHAR[(length)] [BINARY]
[CHARACTER SET charset_name] [COLLATE collation_name]
| VARCHAR(length) [BINARY]
[CHARACTER SET charset_name] [COLLATE collation_name]
| BINARY[(length)]
| VARBINARY(length)
| TINYBLOB
| BLOB
| MEDIUMBLOB
| LONGBLOB
| TINYTEXT [BINARY]
[CHARACTER SET charset_name] [COLLATE collation_name]
| TEXT [BINARY]
[CHARACTER SET charset_name] [COLLATE collation_name]
| MEDIUMTEXT [BINARY]
[CHARACTER SET charset_name] [COLLATE collation_name]
| LONGTEXT [BINARY]
[CHARACTER SET charset_name] [COLLATE collation_name]
| ENUM(value1,value2,value3,...)
[CHARACTER SET charset_name] [COLLATE collation_name]
| SET(value1,value2,value3,...)
[CHARACTER SET charset_name] [COLLATE collation_name]
| JSON
| spatial_type index_col_name:
col_name [(length)] [ASC | DESC] index_type:
USING {BTREE | HASH} index_option:
KEY_BLOCK_SIZE [=] value
| index_type
| WITH PARSER parser_name
| COMMENT 'string' reference_definition:
REFERENCES tbl_name (index_col_name,...)
[MATCH FULL | MATCH PARTIAL | MATCH SIMPLE]
[ON DELETE reference_option]
[ON UPDATE reference_option] reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT table_options:
table_option [[,] table_option] ... table_option:
AUTO_INCREMENT [=] value
| AVG_ROW_LENGTH [=] value
| [DEFAULT] CHARACTER SET [=] charset_name
| CHECKSUM [=] {0 | 1}
| [DEFAULT] COLLATE [=] collation_name
| COMMENT [=] 'string'
| COMPRESSION [=] {'ZLIB'|'LZ4'|'NONE'}
| CONNECTION [=] 'connect_string'
| {DATA|INDEX} DIRECTORY [=] 'absolute path to directory'
| DELAY_KEY_WRITE [=] {0 | 1}
| ENCRYPTION [=] {'Y' | 'N'}
| ENGINE [=] engine_name
| INSERT_METHOD [=] { NO | FIRST | LAST }
| KEY_BLOCK_SIZE [=] value
| MAX_ROWS [=] value
| MIN_ROWS [=] value
| PACK_KEYS [=] {0 | 1 | DEFAULT}
| PASSWORD [=] 'string'
| ROW_FORMAT [=] {DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT}
| STATS_AUTO_RECALC [=] {DEFAULT|0|1}
| STATS_PERSISTENT [=] {DEFAULT|0|1}
| STATS_SAMPLE_PAGES [=] value
| TABLESPACE tablespace_name [STORAGE {DISK|MEMORY|DEFAULT}]
| UNION [=] (tbl_name[,tbl_name]...) partition_options:
PARTITION BY
{ [LINEAR] HASH(expr)
| [LINEAR] KEY [ALGORITHM={1|2}] (column_list)
| RANGE{(expr) | COLUMNS(column_list)}
| LIST{(expr) | COLUMNS(column_list)} }
[PARTITIONS num]
[SUBPARTITION BY
{ [LINEAR] HASH(expr)
| [LINEAR] KEY [ALGORITHM={1|2}] (column_list) }
[SUBPARTITIONS num]
]
[(partition_definition [, partition_definition] ...)] partition_definition:
PARTITION partition_name
[VALUES
{LESS THAN {(expr | value_list) | MAXVALUE}
|
IN (value_list)}]
[[STORAGE] ENGINE [=] engine_name]
[COMMENT [=] 'comment_text' ]
[DATA DIRECTORY [=] 'data_dir']
[INDEX DIRECTORY [=] 'index_dir']
[MAX_ROWS [=] max_number_of_rows]
[MIN_ROWS [=] min_number_of_rows]
[TABLESPACE [=] tablespace_name]
[(subpartition_definition [, subpartition_definition] ...)] subpartition_definition:
SUBPARTITION logical_name
[[STORAGE] ENGINE [=] engine_name]
[COMMENT [=] 'comment_text' ]
[DATA DIRECTORY [=] 'data_dir']
[INDEX DIRECTORY [=] 'index_dir']
[MAX_ROWS [=] max_number_of_rows]
[MIN_ROWS [=] min_number_of_rows]
[TABLESPACE [=] tablespace_name] query_expression:
SELECT ... (Some valid select or union statement)

【Java】-NO.16.EBook.4.Java.1.012-【疯狂Java讲义第3版 李刚】-  JDBC

drop database if exists select_test;
create database select_test;
use select_test;
# 为了保证从表参照的主表存在,通常应该先建主表。
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,
foreign key(java_teacher) references teacher_table(teacher_id)
);
insert into teacher_table values (null , 'Yeeku');

3.2 alter 修改表  

3.2.1 子查询创建表:

CREATE TABLE 新表名 AS SELECT * FROM 旧表;

3.2.2 增加列:

ALTER TABLE tt ADD t_id2 INT;

3.2.3 修改列:

ALTER TABLE tbl_name
[alter_specification [, alter_specification] ...]
[partition_options] alter_specification:
table_options| MODIFY [COLUMN] col_name column_definition
[FIRST | AFTER col_name] ALTER TABLE tt MODIFY t_id2 BIGINT AFTER t_id3, MODIFY t_id3 BIGINT AFTER t_id4;

3.2.4 删除列:

alter table 表名 drop 列名

3.2.5 修改表名:

alter table 旧表名 rename to 新表名

3.2.6 修改列名

alter table 表 change 旧列名 新列名 列属性

3.2.7 删除表

drop table 表名

3.2.8 清空表

truncate 表名

4.约束

【Java】-NO.16.EBook.4.Java.1.012-【疯狂Java讲义第3版 李刚】-  JDBC

【Java】-NO.16.EBook.4.Java.1.012-【疯狂Java讲义第3版 李刚】-  JDBC

  

USE information_schema;
SELECT * FROM table_constraints;

【Java】-NO.16.EBook.4.Java.1.012-【疯狂Java讲义第3版 李刚】-  JDBC

4.1 not null 约束

create table hh(
hh_id not null
)

4.2 unique 约束

create table hh(
hh_name varchar(255) unique
) 多列约束
create table hh(
hh_id int not null,
hh_name varchar(255),
hh_pass varchar(255),
unique(hh_name),
constarint hh_uk unique(test_pass)
) 多列约束,同上
create table hh(
hh_id int not null,
hh_name varchar(255),
hh_pass varchar(255),
constarint hh_uk unique(test_name, test_pass)
)

4.2.1 删除约束

alter table hh drop index hh_uk;

  

4.3 primary 约束

create table hh(
#自增主键约束
hh_id int auto_imcrement primary key,
hh_name varchar(255)
) create table hh(
hh_id int not null,
hh_name varchar(255),
hh_pass varchar(255),
#以下对mysql无效,但对大部分数据库有效
constarint hh_pk primary key(hh_id)
) create table hh(
hh_id int not null,
hh_name varchar(255),
hh_pass varchar(255),
// 多列主键约束
primary key(test_name, test_pass)
)

 

删除主键约束
alter table hh drop primary key; 增加表级主键约束
alter table hh add primary key (test_name, test_pass) 增加列级主键约束
alter table hh modify test_name varchar(255) primary key

  

4.4 foreign key 约束

create table teacher_table(
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 int references teacher_table(teacher_id)
); #应使用以下方式
create table student_table1(
student_id int auto_increment primary key,
student_name varchar(255),
java_teacher int,
foreign key(java_teacher) references teacher_table(teacher_id)
); #单列外键约束
create table teacher_table2(
teacher_id int auto_increment,
teacher_name varchar(255),
primary key(teacher_id)
); create table student_table2(
student_id int auto_increment primary key,
student_name varchar(255),
java_teacher int,
constraint student_teacher_fk foreign key(java_teacher) references teacher_table2(teacher_id)
); #多列外键约束
create table teacher_table3(
teacher_name varchar(255),
teacher_pass varchar(255),
primary key(teacher_id)
); create table student_table3(
student_id int auto_increment primary key,
student_name varchar(255),
student_pass varchar(255),
foreign key(java_teacher_name, java_teacher_pass) references teacher_table3(teacher_name, teacher_pass)
); #删除外键约束
alter table student_table3 drop foreign key student_table3_ibfk_1;
#增加外键约束
alter table student_table3 add foreign key(java_teacher_name, java_teacher_pass) references teacher_table3(teacher_name, teacher_pass); #自关联外键约束
create table foreign_test(
foreign_id int auto_increment primary key,
foreign_name varchar(255),
refer_id int,
foreign key(refer_id) references foreign_test(foreign_id)
); #级联删除,主表删除,从表也跟着删除
create table teacher_table4(
teacher_id int auto_increment,
teacher_name varchar(255),
primary key(teacher_id)
); create table student_table4(
student_id int auto_increment primary key,
student_name varchar(255),
java_teacher int,
foreign key(java_teacher) references teacher_table4 on delete cascade #也可以用on delete set null
);

4.5 check 约束

没卵用

5.索引

create index 索引名 on 表名(列名)
多列索引
create index tb_1 on employees(first_name, last_name);
删除索引
drop index 索引名 on 表名

  

6.视图

#视图数据的逻辑显示,即查询结果,视图不存储数据
create or replace view 视图名
as
subquery create or replace view
as
select teacher_name, teacher_pass from teacher_table
#指定不允许修改视图数据,可选,而oracle则使用with read only
with check option #删除视图
drop view 视图名

  

7.DML

1.
insert into table_name [(column[, column...])] values (value[, value]); insert into student_table2 values(null, '张三', 2); #使用子查询的值插入
insert into student_table2(student_name) select teacher_name from teacher_table2; #同时插入多个值
insert into teacher_table2 values(null, 'a'), (null, 'b'); 2.update
update table set column=value1[, column2=value2]...[where condition] update teacher_table2 set teacher_name = 'ss' where teacher_id > 1; 3. delete from
delete from table_name [where condition] delete from teacher_table where teacher_id > 2; 4. select
select column1, column2 from 数据源 [where condition] 4.1 concat 连接
select concat(teacher_name, 'xx') from teacher_table; 4.2 列 as 别名 或者 空格
select teacher_name as tn from teacher_table;
select teacher_name tn from teacher_table; 4.3 表 别名
select teacher_name tn from teacher_table t; 4.4 去重 distinct
select distinct student_name from student_table; 4.5 判断不相等,可以用 != 也可以用 <>
4.6 赋值用 :=
4.7 between...and ,包含临界,in(...,...) 不包含临界
4.8 like 模糊查询,
'a%' a开头
'__' 任意两个字符
'\_' 转义
标准sql时,需要显示指明转义
like '\_' escape '\'
'4.9 非空判断 is null
4.10 order by [desc|asc] 降序/升序 ,默认升序 5.函数
5.1 char_length() 字符长度
5.2 sin() sin值
5.3
# 增加时间DATE_ADD(),1998-03-02
SELECT DATE_ADD('1998-01-02', INTERVAL 2 MONTH) # 增加时间ADDDATE(),1998-01-05
SELECT ADDDATE('1998-01-02', 3) # 获取当前日期
SELECT CURDATE(); # 获取当前时间
SELECT CURTIME(); # md5
SELECT MD5('ttt')

  

8.....丢失了.....有时间再补

9. jdbc

几个重要的类:

DiverManger

Connection

Statement

PrepareStatement

CallableStatement

Savepoint

ResultSet

ResultSetMateDate

 

9.1

public class ConnMySql
{
public static void main(String[] args) throws Exception
{
// 1.加载驱动,使用反射的知识,现在记住这么写。
Class.forName("com.mysql.cj.jdbc.Driver");
try(
// 2.使用DriverManager获取数据库连接,
// 其中返回的Connection就代表了Java程序和数据库的连接
// 不同数据库的URL写法需要查驱动文档知道,用户名、密码由DBA分配
Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/select_test"
, "root" , "root");
// 3.使用Connection来创建一个Statment对象
Statement stmt = conn.createStatement();
// 4.执行SQL语句
/*
Statement有三种执行sql语句的方法:
1 execute 可执行任何SQL语句。- 返回一个boolean值,
如果执行后第一个结果是ResultSet,则返回true,否则返回false
2 executeQuery 执行Select语句 - 返回查询到的结果集
3 executeUpdate 用于执行DML语句。- 返回一个整数,
代表被SQL语句影响的记录条数
*/
ResultSet rs = stmt.executeQuery("select s.* , teacher_name"
+ " from student_table s , teacher_table t"
+ " where t.teacher_id = s.java_teacher"))
{
// ResultSet有系列的getXxx(列索引 | 列名),用于获取记录指针
// 指向行、特定列的值,不断地使用next()将记录指针下移一行,
// 如果移动之后记录指针依然指向有效行,则next()方法返回true。
while(rs.next())
{
System.out.println(rs.getInt(1) + "\t"
+ rs.getString(2) + "\t"
+ rs.getString(3) + "\t"
+ rs.getString(4));
}
}
}
}

  

public class ExecuteSQL
{
private String driver;
private String url;
private String user;
private String pass;
public void initParam(String paramFile)throws Exception
{
// 使用Properties类来加载属性文件
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
}
public void executeSql(String sql)throws Exception
{
// 加载驱动
Class.forName(driver);
try(
// 获取数据库连接
Connection conn = DriverManager.getConnection(url
, user , pass);
// 使用Connection来创建一个Statement对象
Statement stmt = conn.createStatement())
{
// 执行SQL,返回boolean值表示是否包含ResultSet
boolean hasResultSet = stmt.execute(sql);
// 如果执行后有ResultSet结果集
if (hasResultSet)
{
try(
// 获取结果集
ResultSet rs = stmt.getResultSet())
{
// ResultSetMetaData是用于分析结果集的元数据接口
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// 迭代输出ResultSet对象
while (rs.next())
{
// 依次输出每列的值
for (int i = 0 ; i < columnCount ; i++ )
{
System.out.print(rs.getString(i + 1) + "\t");
}
System.out.print("\n");
}
}
}
else
{
System.out.println("该SQL语句影响的记录有"
+ stmt.getUpdateCount() + "条");
}
}
}
public static void main(String[] args) throws Exception
{
ExecuteSQL es = new ExecuteSQL();
es.initParam("mysql.ini");
System.out.println("------执行删除表的DDL语句-----");
es.executeSql("drop table if exists my_test");
System.out.println("------执行建表的DDL语句-----");
es.executeSql("create table my_test"
+ "(test_id int auto_increment primary key, "
+ "test_name varchar(255))");
System.out.println("------执行插入数据的DML语句-----");
es.executeSql("insert into my_test(test_name) "
+ "select student_name from student_table");
System.out.println("------执行查询数据的查询语句-----");
es.executeSql("select * from my_test");
}
}
public class PreparedStatementTest
{
private String driver;
private String url;
private String user;
private String pass;
public void initParam(String paramFile)throws Exception
{
// 使用Properties类来加载属性文件
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
// 加载驱动
Class.forName(driver);
}
public void insertUseStatement()throws Exception
{
long start = System.currentTimeMillis();
try(
// 获取数据库连接
Connection conn = DriverManager.getConnection(url
, user , pass);
// 使用Connection来创建一个Statment对象
Statement stmt = conn.createStatement())
{
// 需要使用100条SQL语句来插入100条记录
for (int i = 0; i < 100 ; i++ )
{
stmt.executeUpdate("insert into student_table values("
+ " null ,'姓名" + i + "' , 1)");
}
System.out.println("使用Statement费时:"
+ (System.currentTimeMillis() - start));
}
}
public void insertUsePrepare()throws Exception
{
long start = System.currentTimeMillis();
try(
// 获取数据库连接
Connection conn = DriverManager.getConnection(url
, user , pass);
// 使用Connection来创建一个PreparedStatement对象
PreparedStatement pstmt = conn.prepareStatement(
"insert into student_table values(null,?,1)")) {
// 100次为PreparedStatement的参数设值,就可以插入100条记录
for (int i = 0; i < 100 ; i++ )
{
pstmt.setString(1 , "姓名" + i);
pstmt.executeUpdate();
}
System.out.println("使用PreparedStatement费时:"
+ (System.currentTimeMillis() - start));
}
}
public static void main(String[] args) throws Exception
{
PreparedStatementTest pt = new PreparedStatementTest();
pt.initParam("mysql.ini");
pt.insertUseStatement();
pt.insertUsePrepare();
}
}

  【Java】-NO.16.EBook.4.Java.1.012-【疯狂Java讲义第3版 李刚】-  JDBC

public class CallableStatementTest
{
private String driver;
private String url;
private String user;
private String pass;
public void initParam(String paramFile)throws Exception
{
// 使用Properties类来加载属性文件
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
}
public void callProcedure()throws Exception
{
// 加载驱动
Class.forName(driver);
try(
// 获取数据库连接
Connection conn = DriverManager.getConnection(url
, user , pass);
// 使用Connection来创建一个CallableStatment对象
CallableStatement cstmt = conn.prepareCall(
"{call add_pro(?,?,?)}"))
{
cstmt.setInt(1, 4);
cstmt.setInt(2, 5);
// 注册CallableStatement的第三个参数是int类型
cstmt.registerOutParameter(3, Types.INTEGER);
// 执行存储过程
cstmt.execute();
// 获取,并输出存储过程传出参数的值。
System.out.println("执行结果是: " + cstmt.getInt(3));
}
}
public static void main(String[] args) throws Exception
{
CallableStatementTest ct = new CallableStatementTest();
ct.initParam("mysql.ini");
ct.callProcedure();
}
}

  

9.2 管理结果集

【Java】-NO.16.EBook.4.Java.1.012-【疯狂Java讲义第3版 李刚】-  JDBC

  

 

  

  

上一篇:关于sharedPreferences的使用


下一篇:使用Ramdisk 加速 Visualstudio 编译调试