主頁 >  其他 > 資料庫

資料庫

2020-10-19 23:12:33 其他

資料庫基礎筆記


博客目錄

在這里插入圖片描述

一、創建表:

注釋:用 – 或則 /**/
sql關鍵字大小寫不敏感,建議小寫,所有符號全部用英文,

create table if not exists 表名(
   `欄位名`  列型別  [屬性]  [索引]  [注釋],
    `欄位名`  列型別  [屬性]  [索引]  [注釋],
    ..............
    `欄位名`  列型別  [屬性]  [索引]  [注釋],
   PRIMARY KEY(`id`)
)
create table if not exists student(
		`id`   int(4) NOT NULL AUTO_INCREMENT COMMENT '學號',
		`name` VARCHAR(20) NOT NUll DEFAULT '匿名' COMMENT '姓名',
		`pwd`  VARCHAR(20) NOT NUll DEFAULT '123456' COMMENT '密碼',
		`sex`  VARCHAR(2)  NOT NULL DEFAULT '女' COMMENT '性別',
		`birthday` DATETIME DEFAULT NULL COMMENT '出生日期',
		`address` VARCHAR(100) DEFAULT NULL COMMENT '家庭住址',
		`email` VARCHAR(50) DEFAULT NULL COMMENT '郵箱',
		PRIMARY KEY(`id`)--主鍵
)ENGINE=INNODB DEFAULT CHARSET=utf8;--資料庫引擎和字符編碼
/*
CHARSET=utf8
不設定的話,會是mysql默認的字符集編碼~(不支持中文!)
MySQL的默認編碼是Latin1,不支持中文
*/
SHOW CREATE database ;資料庫名/*查看資料庫如何創建*/
CREATE DATABASE `westos`/*!40100 DEFAULT CHARACTER SET utf8 */
SHOW CREATE TABLE 表名;/*查看創建表的陳述句*/
DESC 表名;/*查看表的結構*/

資料引擎:

INNODBMYISAM
事物支持支持不支持
資料庫行鎖支持不支持
外鍵支持不支持
全文索引不支持支持
表空間大小較小較大,約為2倍

常規操作:
(1)INNODB:安全性高,事物的處理,多表多用戶;
(2)MYISAM:節約空間,速度較快
所有的資料庫檔案存在data目錄下,本質上還是檔案存盤,


二、修改表:

--修改表名: alter table 舊表名 RENAME AS 新表名
alter TABLE user RENAME AS user1;
--增加表的欄位: ALTER TABLE 表名 add 欄位名 列屬性
alter TABLE user1 add age INT(11);
--修改表的欄位(重命名,修改約束!)
ALTER TABLE user1 MODIFY age VARCHAR(11);--修改約束
ALTER TABLE user1 change age agel INT(1);--欄位重名名
--洗掉表的欄位
alter TABLE user1 drop age1;
--洗掉表
drop TABLE if exists user1;

三、MySQL資料庫管理

3.1外鍵(了解):
/*方式一*/
--學生表的 gradeid欄位要去參考年級表的gradeid
--定義外鍵key
--給這個外鍵添加約束(執行參考)references參考
create table if not exists student(
		`id`   int(4) NOT NULL AUTO_INCREMENT COMMENT '學號',
		`name` VARCHAR(20) NOT NUll DEFAULT '匿名' COMMENT '姓名',
		`pwd`  VARCHAR(20) NOT NUll DEFAULT '123456' COMMENT '密碼',
		`sex`  VARCHAR(2)  NOT NULL DEFAULT '女' COMMENT '性別',
		`birthday` DATETIME DEFAULT NULL COMMENT '出生日期',
		`address` VARCHAR(100) DEFAULT NULL COMMENT '家庭住址',
		`email` VARCHAR(50) DEFAULT NULL COMMENT '郵箱',
		`gradeid` INT(10) NOT NULL COMMENT '學生的年級',
		PRIMARY KEY(`id`),
		KEY `fk_grade` (`gradeid`),
		CONSTRAINT `fk_grade_id` FOREIGN KEY (`gradeid`) REFERENCES `grade`(`gradeid`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

CREATE TABLE `grade`(
`gradeid` INT(10) NOT NULL AUtO_INCREMENT COMMENT '年級id',
`gradename` VARCHAR(50) NOT null COMMENT '年級名稱',
PRIMARY KEY(`gradeid`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
/*
洗掉有外鍵關系的表的時候,必須要先洗掉參考別人的表(從表),再洗掉被參考的表(主表)
*/
/*方式二*/
--創建表成功后,添加外鍵約束
--創建表的時候沒有外鍵關系
ALTER TABLE `student`
ADD CONSTRAINT `FK_gradeid` FOREIGN KEY( `gradeid` ) REFERENCES `grade` ( `gradeid`);
--ALTER TABLE 表ADD CONSTRAINT約束名FOREIGN KEY(作為外鍵的列)REFERENCES那個表(哪個欄位)

以上的操作都是物理外鍵,資料庫級別的外鍵,我們不建議使用!(避免資料庫過多造成困擾)
最佳方法
資料庫就是單純的表,只用來存資料,只有行(資料)和列(欄位)
我們想使用多張表的資料,想使用外鍵(程式去實作)

3.2、DML語言(資料庫操作語言)

資料庫意義:資料存盤,資料管理

1、添加(insert)
--插入陳述句(添加)
-- insert into表名([欄位名1,欄位2,欄位3]) values('值1','值2','值3,...)
insert into `grade`(`gradename`) values ('大學')
--由于主鍵自增我們可以省略(如果不寫表的欄位,他就會——匹配)
insert into `grade` values ('高中')
--一般寫插入陳述句,我們一定要資料和欄位——對應!
/*插入多條陳述句*/
insert into `grade`(`gradename`,`gradenum`) values ('大一',52),('大二',52);
/*
注意事項:
1.欄位和欄位之間使用英文逗號隔開
2.欄位是可以省略的,但是后面的值必須要和資料庫定義欄位一一對應,不能少
3.可以同時插入多條資料,VALUES后面的值,需要使用,隔開即可 values(),(),....
*/
2、修改(update)
/*修改陳述句*/
/*
兩種理解:
語法1:update 表名 set 欄位1=修改值, 欄位2=修改值,....... where 條件;
語法2:update 表名 set colnum_name1=value, colnum_name2=value,....... where 條件;
*/
update `student` set `name`='小吳呀',`sex`='女' where `id`=1;
--不指定條件的情況下會改動所有表
update update `student` set `name`='小吳呀',`sex`='女' 
/*
注意:
colnum_name是資料庫的列,盡量帶上``
條件,篩選的條件,如果沒有指定,則會修改所有的列
value,是一個具體的值,也可以是一個變數
設定多個欄位的值使用英文逗號隔開
UPDATE ‘student’ SET birthday'= CURRENT_TIME WHERE name'='長江7號’AND sex='女'
*/
3、洗掉(delete)
/*洗掉資料*/
/*
語法:delete from 表名 where 條件;
*/
--洗掉資料(避免出現這樣的情況,會全部洗掉)
delete from `student`
--洗掉指定資料
delete from `student` where id=1;
/*清空一個表中資料的方法*/
--Truncate 表名;
truncate `student`;
/*
delete和truncate洗掉表的區別
1.delete from 表名;
  洗掉資料不會影響主鍵的自增
2.Truncate 表名;
  洗掉資料后主鍵的自增會歸零,也就是說會影響到主鍵的自增
*/

了解即可:DELETE洗掉的問題,重啟資料庫,現象
INNODB:自增列會重1開始―(存在記憶體當中的,斷電即失)
MylSAM:繼續從上一個自增量開始(存在檔案中的,不會丟失)


3.3、DQL查詢資料(資料庫查詢語言)
1、基礎查詢語法
/*查詢陳述句結構和位置*/
SELECT [ALL l DISTINCT]
{* l table.* / [table.field1[as alias1][,table.field2[as alias2]][...]]]}
FROM table_name [as tab1e_alias]
[left / right l inner join table_name2]--聯合查詢
[WHERE ...]--指定結果需滿足的條件
[GROUP BY ...]--指定結果按照哪幾個欄位來分組
[HAVING]--過濾分組的記錄必須滿足的次要條件
[ORDER BY ...]--指定查詢記錄按一個或多個條件排序
[LIMIT {[offset,]row_count l row_countOFFSET offset}];
--指定查詢的記錄從哪條至哪條

/*查詢陳述句*/
--查詢所有的資訊
select*from student;
--查詢指定欄位
select `studentnumber`,`studentname` from `student`;
--給欄位起別名,用AS,也可以給表起別名,用AS
select `studentnumber` as 學號,`studentname` as 姓名 from `student`;
--函式 拼接字串Concat(a,b)
select CONCAT('姓名:',studentname) AS 新名字 from student;

2、去重:distinct
--查詢哪些同學參加了考試
select `studentnumber` from result;
select DISTINCT `studentnumber` from result;--去掉重復的資料
select version();--查詢mysql系統版本
select 100*3-1 AS 計算結果;--用于計算
select @@auto_increment_increment;--查詢自增的步長
/*將學生的成績加一分*/
select `studentnumber`,`studentresult`+1 as '加分后' from result;
3、where條件子句

作用:檢索資料中符合條件的值
(1)邏輯運算子

運算子語法描述
and &&a and b a&&b邏輯與 兩個都為真結果為真
or ||a or b a||b邏輯或 其中一個為真結果為真
not !not a !a邏輯非 真為假 ,假為真
--and和&& 兩者可以互換
select studentno,studentresult from result 
where 80<studentresult and studentresult<100;
--查詢區間(between...and...)
select studentno,studentresult from result 
where studentresult between 70 and 100;
--not和!= 
select studentno,studentresult from result 
where not studentno=1000;
select studentno,studentresult from result 
where  studentno!=1000;

(2)比較運算子(模糊查詢)

運算子語法描述
IS NULLa is null如果運算子為NULL,結果為真
IS NOT NULLa is not null如果運算子不為空,結果為真
BETWEENa between b and c如在b和c之間,則結果為真
Likea like bSQL匹配,如果a匹配b,則結果為真
INa in(a1,a2,a3)假設a在a1或者a2…其中的某一個值,結果為真
/*模糊查詢*/
--查詢姓羅的同學,like結合 %(代表0到任意個字符) _代表一個字符
select `studentno`, `studentname` from student 
where studentname like '羅%';--查詢名字為任意多個字的并且姓羅
select `studentno`, `studentname` from student 
where studentname like '羅_';--查詢名字為兩個字的并且姓羅
select `studentno`, `studentname` from student 
where studentname like '%羅%';--查詢名字中帶有羅字的人
--in
select  `studentno`, `studentname` from student
where studentno in(1001,1002,1003);--查詢序號為1001,1002,1003的學生
--null   not null
select  `studentno`, `studentname`,`address` from student
where  address='' or address is null;--查詢地址為空的記錄
select  `studentno`, `studentname`,`address`,`birthday` from student
where birthday is not null ;--查詢出生日期不為空的人
4、聯表查詢

學生科目表(subject):
在這里插入圖片描述

學生資訊表(student):
在這里插入圖片描述

學生成績表(result):
在這里插入圖片描述

 /*查詢參加了考試的學生(學號,姓名,科目編號,分數)*/
 --inner join
 select s.studentno,studentname,subjectno,studentresult 
 from student as s inner join result as r 
 where s.studentno=r.studentno;
--right join(左連接)
 select s.studentno,studentname,subjectno,studentresult 
 from student as s right join result as r 
 on s.studentno=r.studentno;
 --left join(右連接)
 select s.studentno,studentname,subjectno,studentresult 
 from student as sleft join result as r 
 on s.studentno=r.studentno;
 /*
 查詢參加考試同學的資訊:學號,學生姓名,科目名,分數
 (學號,學生姓名)來自student表,(科目名)來自subject表,(學號,分數)來自result表
 */
 select s.studentno,studentname,subjectname,studentresult 
 from student s 
 right join result r 
 on s.studentno=r.studentno
 inner join subject sub
 on r.subjectno=sub.subjectno;
操作描述
inner join如果表中至少有一個匹配就回傳
left join會從左表中回傳所有的值,即使右表中沒有匹配
right join會從右表中回傳所有的值,即使左表中沒有匹配

自連接(了解):

自己的表和自己的表連接,本質:一張表拆為一樣的表即可

5、分頁和排序

排序

/*
排序:升序 ASC       		降序:DESC
語法:order by 排序欄位  升序(降序) 
*/
 select s.studentno,studentname,subjectname,studentresult 
 from student s 
 right join result r 
 on s.studentno=r.studentno
 inner join subject sub
 on r.subjectno=sub.subjectno
 order by studentresult DESC;

分頁

/*
limit 起始值(從哪條資料[資料的下標是從0開始的]開始查)  查詢資料條數
第一頁  limit 0,5     (1-1)*5
第二頁  limit 5,5     (2-1)*5
第三頁  limit 10,5     (3-1)*5
第N頁  limit 0,5     (n-1)*pagesize
[pagesize:頁面包含多少條資料,(n-1)*pagesize 起始, n當前頁碼 ,資料總數/頁面大小=總頁數]
*/
 select s.studentno,studentname,subjectname,studentresult 
 from student s 
 right join result r 
 on s.studentno=r.studentno
 inner join subject sub
 on r.subjectno=sub.subjectno
 order by studentresult DESC
 limit 0,2;
/*
題目:查詢java程式設計-1課程成績排名前十的學生,并且要求分數要大于80分(學號,姓名,課程名稱,分數)
*/
select s.studentno,studentname,subjectname,studentresult
from student s
inner join result r 
on s.studentno=r.studentno
inner join subject sub
on r.subjectno=sub.subjectno
where subjectname='java程式設計-1' 
and studentresult>=80
order by studentresult DESC
limit 0,10;

6、子查詢

也叫嵌套查詢,在where中在嵌套查詢陳述句

/*
查詢高等數學-1的所有考試結果(學號,科目編號,科目名稱,成績)按成績升序排列;
*/
--方式一:非子查詢(鏈表查詢)
select studentno,r.subjectno,subjectname,studentresult
from result r
inner join subject sub
on r.subjectno=sub.subjectno
where subjectname='高等數學-1'
order by studentresult ASC
--方式二:子查詢
select studentno,subjectno,studentresult
from result
where subjectno=(
select subjectno from subject where subjectname='高等數學-1'
)
order by studentresult ASC
/*查詢高等數學-1分數不小于70分的學號,姓名,成績并升序排列*/
--子查詢一
select distinct r.studentno,studentname,studentresult
from student s
inner join result r
on r.studentno=s.studentno
where studentresult>70 
and subjectno=(select subjectno from subject where subjectname='高等數學-1')
order by studentresult ASC
/*查詢高等數學-1分數不小于70分的學號,姓名*/
--子查詢二
select  studentno,studentname
from student 
where studentno 
in(select studentno from result where studentresult>70 
  and subjectno=(select subjectno from subject where subjectname='高等數學-1'))
  
  
7、mysql函式

常用函式

/*數學運算*/
select abs(-8) --8 取絕對值
select celling(9.4) --10  向上取整
select floor(9.4) --9  向下取整
select rand() --回傳一個0~1的亂數
select sing(10) --1判斷一個數的符號,負數回傳-1,正數回傳1,0回傳0;
/*字串函式*/
select char_length('小吳呀')--3 回傳字串長度
select concat('惜','君','呀') --'惜君呀'  字串拼接
select lower('AIniyo')--ainiyo 大寫字母轉小寫
select upper('xiaoyanzi')--XIAOYANZI 小寫字母轉大寫
select instr('luobo','o')--3  回傳第一次出現的字母的索引
select replace('java學習','學習','學習要堅持')--'java學習要堅持'   替換
select substr('java學習',2,3)--ava 從第二個開始截取三個字符
select reverse('miss you')--uoy ssim 字串反轉
/*時間日期*/
select current_date()--獲取當前日期
select now()--獲取當前詳細時間(年月日時分秒)
select localtime() --獲取本地時間

聚合函式

函式名稱作用
count()用于計數
sum()用于求和
avg()用于求平均值
max()、min()用于求最大值和最小值
/*聚合函式的使用*/
select count(studentname) from student;--count(指定列的欄位),忽略所用null值
select count(*) from student;--不會忽略null值,本質計算行數;
select count(1) from student;--不會忽略null值,本質計算行數;
select sum(studentresult) as 求和 from result;
select avg(studentresult) as 平均分 from result;
select max(studentresult) as 最大值 from result;
select min(studentresult) as 最小值 from result;
/*查詢不同課程的平均分,最高分,最低分*/
--group by 欄位名:表示通過什么分組,分組后可用having進行條件控制
select subjectname,max(studentresult) as 最高分,min(studentresult) as 最低分,avg(studentresult) as 平均分
from result r
inner join subject sub
on r.subjectno=sub.subjectno
group by r.subjectno
having 平均分>80

在這里插入圖片描述

四、資料庫級別的MD5加密

/*建測驗表*/
create table testmd5(
		id int(4) not null,
		name VARCHAR(20) not null,
		pwd VARCHAR(50) not null,
		PRIMARY KEY(id)
)ENGINE=INNODB DEFAULT CHARSET=utf8
--插入資料
insert into testmd5 VALUES(1 ,'小吳','123'),(2 ,'小網','1234'),(3 ,'小嘿','1235')
--加密id=1 的資料
update testmd5 set pwd=MD5(pwd) where id=1;
--加密所有密碼
update testmd5 set pwd=MD5(pwd)
--資料插入時加密
insert into testmd5 values (4,'微末',MD5("123456"))

五、資料庫的事物

5.1、事物:

一組sql操作要么都成功,要么都失敗.

事物的原則:ACID原則(原子性、一致性、隔離性、持久性)
原子性:事物要么全部被執行,要么全部不執行,
一致性:事物的執行使得資料庫的狀態從一種正確狀態轉變成另外一種正確狀態(也就是事物執行前后資料完整 性保持一致),
隔離性:事物在正確提交之前,不允許把該事物對資料的修改提供給其他任何事物(也就是說在執行程序中的所 有東西都是私有的,不允許給別人看),
持久性:事物沒有提交,恢復到執行事物之前的狀態,事物正確提交,資料持久化到資料庫,(一旦提交不可 逆)

隔離性產生的問題:
臟讀一個事物讀取了另外一個事物未提交的資料,
不可重復讀:一個事物兩次讀取同一個資料,兩次讀取的資料不一樣(資料被其他事物修改),
幻讀:一個事物兩次讀取同一個范圍的記錄,兩次讀取的記錄數不一樣(別的事物可能新插入了資料導致前后數 據的條數不一樣),

/*事物*/
--MySQL資料庫默認是開啟事物的提交的
set autocommit=0 --關閉事物自動提交
set autocommit=1 --開啟事物自動提交(MySQL默認開啟)
/*手動處理事物*/
--1.關閉自動提交
set autocommit=0
--2.開啟事物
start transaction --標記事物的開始,從該陳述句過后所有執行的sql陳述句都在同一個事物中
--3.執行具體的sql陳述句
insert xxx;
insert xxx;
--4.提交:持久化(成功)
commt
--5.回滾:回到事物執行的最初狀態(事物執行失敗才回滾)
rollback
--6.事物結束開啟自動提交
set autocommit=1
/*了解*/
savepoint 保存點名 --設定一個事物的保存點
rollback to savepoint 保存點名 --回滾到保存點
release savepoint 保存點名 --撤銷保存點
/*模擬事物場景(轉賬)*/
創建一張表
create table account(
`id` int(4) NOT null AUTO_INCREMENT,
`name` VARCHAR(30) NOT NULL,
`money` DECIMAL(9,2),
PRIMARY key(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
--插入兩條資料
INSERT into account(name,money) VALUES ('秋',200),('春',100);

set AUTOCOMMIT=0; --1.關閉事物自動提交
START TRANSACTION;--2.開啟一個事物
--3.執行sql陳述句
update account set money=money-50 where name='A';
update account set money=money+50 where name='B';
--4.事物正確提交后執行
COMMIT
--5.事物為正確提交執行
ROLLBACK
--6.開啟事物自動提交
set autocommit=1;

六、資料庫索引

索引的定義:索引(index)是幫助MySQL高效獲取資料的資料結構,提取句子主干,就可以得到索引的本質:索引是 資料結構,

6.1索引分類
  • 主鍵索引(primary key)
    唯一的標識,主鍵不可重復只能有一個列作為主鍵

  • 唯一索引(unique key)
    避免重復的列出現,唯一索引可以重復,多個列可以標識為唯一索引

  • 常規索引(key/index)
    默認的,index、key關鍵字來設定

  • 全文索引(fulltext)
    在特定的資料庫引擎下才有,如MyISAM
    快速定位資料

在一個表中主鍵索引只能有一個,唯一索引可以有多個

/*索引的使用*/
--1.創建表的時候給欄位增加索引     2.創建完畢后增加索引
--顯示所有的索引資訊
show index from student;
--給student表增加一個全文索引
alter table student add fulltext index studentname(studentname)
--explain分析sql執行的情況
explain select*from student;--非全文所引
explain select*from student where match(studentname) against('趙');

所引在資料量小的時候用處不大,但是在資料量較大時區別就十分明顯

6.2、索引原則

1.索引不是越多越好,不要對經常變動的資料加索引
2.小資料量的表不需要加索引
3.索引一般加在常用來查詢的欄位上
索引的資料結構
btree:innoDB的默認資料結構
詳解:http://blog.codinglabs.org/articles/theory-of-mysql-index.html

七、資料庫三范式

7.1、資料庫三范式
1.第一范式(1NF)

原子性:保證每一列不可再分

2.第二范式(2NF)

前提:滿足第一范式
表必須有一個主鍵,沒有包含在主鍵中的列必須完全依賴于主鍵,而不能只依賴于主鍵的一部分,

3.第三范式(3NF)

前提:滿足第一范式和第二范式
非主鍵列必須直接依賴于主鍵,不能存在傳遞依賴,即:不存在非主鍵列A依賴于非主鍵列B,非主鍵列B依賴于主鍵的情況,

7.2、規范性和性能的問題

關聯查詢的表最好不得超過三張表
1.考慮商業化的需求和目標,(成本,用戶體驗!)資料庫的性能更加重要
2.在規范性能的問題的時候,需要適當的考慮一下規范性!
3.故意給某些表增加一些冗余的欄位,(從多表查詢中變為單表查詢)
4.故意增加—些計算列(從大資料量降低為小資料量的查詢:索引)

八、JDBC(重點)

8.1、資料庫驅動

JDBC:java操作資料庫的規范
JDBC編程還需匯入一個驅動包:mysql-connector-java-5.1.47.jar

1.java中JDBC編程測驗

測驗表(users):
在這里插入圖片描述

public class JdbcTest {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加載資料庫驅動
        Class.forName("com.mysql.jdbc.Driver");
        //2.用戶的資訊和URL
        String url="jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String username="root";
        String password="123";
        //3.連接成功,資料庫物件
        Connection connection = DriverManager.getConnection(url, username, password);
        //4.執行sql的物件
        Statement statement = connection.createStatement();
        //5.執行sql物件去執行sql,存在結果查看結果回傳集
        String sql="select*from users";
       //該陳述句中封裝了全部的查詢結果
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            System.out.println("id="+resultSet.getObject("id"));
            System.out.println("name="+resultSet.getObject("name"));
            System.out.println("password="+resultSet.getObject("password"));
            System.out.println("email="+resultSet.getObject("email"));
            System.out.println("birthday="+resultSet.getObject("birthday"));
            System.out.println("-----------------------------");
       }
        //釋放連接(關閉順序倒著來,最先開啟的最后關閉)
          resultSet.close();
          statement.close();
          connection.close();
    }
}
//執行結果
id=1
name=zhangsan
password=123456
email=zs@qq.com
birthday=1995-08-12
-----------------------------
id=2
name=lisi
password=123456
email=lisi@qq.com
birthday=1996-08-12
-----------------------------
id=3
name=luo
password=123456
email=luo@qq.com
birthday=1997-08-12
-----------------------------
2.撰寫步驟

1、加載驅動
2、連接資料庫DriverManager
3、獲得執行sql的物件Statement
4、獲得回傳的結果集
5、釋放連接

statement.executeQuery();//查詢操作回傳Resultset
statement.execute(); //執行任何SQL
statement.executeUpdate();//更新、插入、洗掉,都是用這個,回傳一個受影響的行數
/*結果集處理*/
resu1tset.getobject(); //在不知道列奚型的情況下使用
//如果知道列的型別就使用指定的型別
resultset.getstring;
resultset.getInt(;
resu1tset.getF1oat(;
resu1tset.getDate(;
resu1tset.getobject;
/*遍歷條件*/
resultset.beforeFirst();//移動到最前面
resultset.afterLast();//移動到最后面
resultset.next();//移動到下一個資料
resultset.previous();//移動到前一行
resu1tset.absolute(row);//移動到指定行
3、封裝JDBCUtils工具類
//file檔案中
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123
/*工具類*/
public class JDBCUtils {
    private static String driver=null;
    private static String url=null;
    private static String username=null;
    private static String password=null;
    static{
        InputStream in=JDBCUtils.class.getClassLoader().getResourceAsStream("com\\lb\\db.properties");
        Properties properties = new Properties();
        try {
            properties.load(in);
            driver=properties.getProperty("driver");
            url=properties.getProperty("url");
            username=properties.getProperty("username");
            password=properties.getProperty("password");
            //驅動只用加載一次
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //獲取連接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }
    //釋放連接資源
    public static void release(Connection con, Statement statement, ResultSet rs)  {
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(con!=null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }
}

測驗增加一個用戶

/*通過封裝的工具類來進行資料庫的操作代碼量明顯減少*/
public class TestInsert {
    public static void main(String[] args) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            con = JDBCUtils.getConnection();//獲取資料庫連接
            st = con.createStatement();//獲取sql的執行物件
            String sql = "insert into users(id,name,password,email,birthday) values (4,'燕子','123456','yz@qq.com','1999-10-18')";
            int i = st.executeUpdate(sql);
            if (i > 0) {
                System.out.println("添加成功");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.release(con, st, rs);
        }
    }
}
//測驗結果:
   添加成功

測驗修改一個用戶

public class TestUpdate {
    public static void main(String[] args) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            con = JDBCUtils.getConnection();//獲取資料庫連接
            st = con.createStatement();//獲取sql的執行物件
            String sql = "update users set name='lb',password='123',email='lb@qq.com',birthday='1997-07-15' where id=3";
            int i = st.executeUpdate(sql);
            if (i > 0) {
                System.out.println("修改成功");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.release(con, st, rs);
        }
    }
//測驗結果:
   修改成功

總結:
用戶的增刪改都用:executeUpdate(sql)
用戶的查詢使用:executeQuery(sql) 查詢后會回傳一個結果集(ResultSet)然后通過結果集將資料拿到

4、sql注入問題(Statement)

sql存在漏洞,可能會被攻擊導致資料泄漏問題

//sql注入的問題(拼接字串)
public class SqlDanger {
public static void main(String[] args) {
  //login("lb","123");//正常登陸(select *from users where name='"+lb+"' and password='"+123456+"')
  //login(" 'or'1=1","123456");//sql注入(select *from users where name='"+ 'or'1=1+"' and password='"+password+"')
  login(" 'or'1=1","  'or'1=1");//sql注入(select *from users where name='"+ 'or'1=1+"' and password='"+ 'or'1=1+"')
}

//模擬登陸
public static void login(String username,String password){
  Connection con = null;
  Statement st = null;
  ResultSet rs = null;
  try {
      con = JDBCUtils.getConnection();//獲取資料庫連接
      st = con.createStatement();//獲取sql的執行物件
      String sql = "select *from users where name='"+username+"' and password='"+password+"'";
        rs = st.executeQuery(sql);
      while (rs.next()){
          System.out.println("id="+rs.getObject("id"));
          System.out.println("name="+rs.getObject("name"));
          System.out.println("password="+rs.getObject("password"));
          System.out.println("email="+rs.getObject("email"));
          System.out.println("birthday="+rs.getObject("birthday"));
          System.out.println("-----------------------------");
      }
  } catch (SQLException throwables) {
      throwables.printStackTrace();
  } finally {
      JDBCUtils.release(con, st, rs);
  }

}
}

5、防止sql注入(PreparesStatement物件)

PreparesStatement物件可以有效防止Sql注入問題,執行效率更高,它會把傳遞進來的引數當做字符直接轉義,

以增刪改查為列
1.新增

public class TestInsert {
public static void main(String[] args) {
  Connection con = null;
  PreparedStatement st = null;
  ResultSet rs = null;
  try {
      con = JDBCUtils.getConnection();//獲取資料庫連接
      //使用英文?占位符代替引數
      String sql = "insert into users(id,name,password,email,birthday) values (?,?,?,?,?)";
      st=con.prepareStatement(sql);//預編譯程序先寫SQL并不會執行
      //設定問好所對應的的值,sql陳述句中引數是什么型別就設定為什么型別
      //set..設定引數說明:第一個代表sql中SQL的問號處于第幾個位置,第二個代表相應問號所對應的的引數型別
      st.setInt(1,5);
      st.setString(2,"干將莫邪");
      st.setString(3,"123456");
      st.setString(4,"gjmy@qq,com");
      // new Date 指的是sql資料庫的時間是java.sql中的
      //new java.util.Date() 是java中的包為java.util.*     getTime()獲取當前時間
      st.setDate(5, new Date(new java.util.Date().getTime()));
      int i = st.executeUpdate();
      if (i > 0) {
          System.out.println("添加成功");
      }
  } catch (SQLException throwables) {
      throwables.printStackTrace();
  } finally {
      JDBCUtils.release(con, st, rs);
  }
}
}

2.洗掉

public class TestDelete {
   public static void main(String[] args) {
       Connection con = null;
       PreparedStatement st = null;
       ResultSet rs = null;
       try {
           con = JDBCUtils.getConnection();//獲取資料庫連接
           //使用英文?占位符代替引數
           String sql = "delete from users where id=?";
           st=con.prepareStatement(sql);//預編譯程序先寫SQL并不會執行
           //設定問好所對應的的值,sql陳述句中引數是什么型別就設定為什么型別
           //set..設定引數說明第一個代表sql中SQL的問號處于第幾個位置,第二個代表相應問號所對應的的引數型別
           st.setInt(1,2);
           int i = st.executeUpdate();
           if (i > 0) {
               System.out.println("洗掉成功");
           }
       } catch (SQLException throwables) {
           throwables.printStackTrace();
       } finally {
           JDBCUtils.release(con, st, rs);
       }
   }
}

3.修改

public class TestUpdate {
   public static void main(String[] args) {
       Connection con = null;
       PreparedStatement st = null;
       ResultSet rs = null;
       try {
           con = JDBCUtils.getConnection();//獲取資料庫連接
           //使用英文?占位符代替引數
           String sql = "update users set name=?,password=?,email=?,birthday=? where id=?";
           st=con.prepareStatement(sql);//預編譯程序先寫SQL并不會執行
           //設定問好所對應的的值,sql陳述句中引數是什么型別就設定為什么型別
           //set..設定引數說明第一個代表sql中SQL的問號處于第幾個位置,第二個代表相應問號所對應的的引數型別
           st.setString(1,"百里守約");
           st.setString(2,"666666");
           st.setString(3,"百里守約@qq,com");
           // new Date 指的是sql資料庫的時間是java.sql中的
           //new java.util.Date() 是java中的包為java.util.*     getTime()獲取當前時間
           st.setDate(4, new Date(new java.util.Date().getTime()));
           st.setInt(5,1);//修改id=1的資料

           int i = st.executeUpdate();
           if (i > 0) {
               System.out.println("修改成功");
           }else {
               System.out.println("修改失敗");
           }
       } catch (SQLException throwables) {
           throwables.printStackTrace();
       } finally {
           JDBCUtils.release(con, st, rs);
       }
   }
}

結果:
執行前在這里插入圖片描述
執行后在這里插入圖片描述
4.查詢

public class TestSelect {
   public static void main(String[] args) {
       Connection con = null;
       PreparedStatement st = null;
       ResultSet rs = null;
       try {
           con = JDBCUtils.getConnection();//獲取資料庫連接
           //使用英文?占位符代替引數
           String sql = "select *from users";
           st=con.prepareStatement(sql);//預編譯程序先寫SQL并不會執行
           rs=st.executeQuery();
           while (rs.next()){
               System.out.println(rs.getString("name")+"\t"+
                                  rs.getString("password")+"\t"+
                                  rs.getString("email") +"\t"+
                                  rs.getDate("birthday"));
           }
       } catch (SQLException throwables) {
           throwables.printStackTrace();
       } finally {
           JDBCUtils.release(con, st, rs);
       }
   }
}

總結:
1.獲取連接獲取資料庫連接 con = JDBCUtils.getConnection();

2.撰寫SQL陳述句( 使用英文?占位符代替引數)

3.sql的預編譯程序 con.prepareStatement(sql);

4.設定對應引數的值 (例如一個String型別,st.setString(1,“百里守約”);)

5.處理相應的結果,若是st.executeQuery()則需遍歷結果集物件,若是st.executeUpdate()則需判斷回傳值是否大于0,大于0表示對資料庫的行數有影響,`

九、資料庫連接池

程序:資料庫的連接 –>執行完畢–>釋放資源,
連接–>釋放:該程序是一個十分浪費資源的程序,
池化技術:準備一些預先的資源,當需要的時候可以直接從準備好的池中拿,
一個池中有:最小連接數(基本)、最大連接數(最大負載)、等待超時

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/180991.html

標籤:其他

上一篇:mysql中,information_schema初探

下一篇:mysql基礎操作遇到的問題

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more