資料庫基礎筆記
博客目錄
:
一、創建表:
注釋:用 – 或則 /**/
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 表名;/*查看表的結構*/
資料引擎:
| INNODB | MYISAM | |
|---|---|---|
| 事物支持 | 支持 | 不支持 |
| 資料庫行鎖 | 支持 | 不支持 |
| 外鍵 | 支持 | 不支持 |
| 全文索引 | 不支持 | 支持 |
| 表空間大小 | 較小 | 較大,約為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 NULL | a is null | 如果運算子為NULL,結果為真 |
| IS NOT NULL | a is not null | 如果運算子不為空,結果為真 |
| BETWEEN | a between b and c | 如在b和c之間,則結果為真 |
| Like | a like b | SQL匹配,如果a匹配b,則結果為真 |
| IN | a 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基礎操作遇到的問題



